2017-04-06 70 views
1

我想创建一个包含多个复选框的项目的表格,如果这些复选框被选中,我想通过按钮单击更新这些项目。Django:只更新被检查的项目

我已经有了一个更新视图,但只有一个项目,并且只有当这个项目的保存按钮被按下时(每个表项都有它自己的按钮)。我的代码如下所示:

<table> 
    <thead> 
    <tr> 
     <th colspan="4"> 
     <button type "submit">My Submit Button</button> 
     </th> 
    </tr> 
    <tr> 
     <th colspan="2">My Title</th> 
     <th>Movie title</th> 
     <th>Movie description</th> 
     <th>And so on</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <th> 
     <input type="checkbox" class="custom-control-input"> 
     </th> 
     <th>Data</th> 
     <th>Data</th> 
     <th>Data</th> 
     <th>Data</th> 
     <th> 
     <button>Button to edit this row item</button> 
     </th> 
     <th> 
     <button type="submit" form="movie{{ forloop.counter }}">Button to save the changes</button> 
     </th> 
    </tr> 
    <tr> 
     <th> 
     <input type="checkbox" class="custom-control-input"> 
     </th> 
     <th>Data</th> 
     <th>Data</th> 
     <th>Data</th> 
     <th>Data</th> 
     <th> 
     <button>Button to edit this row item</button> 
     </th> 
     <th> 
     <button type="submit" form="movie{{ forloop.counter }}">Button to save the changes</button> 
     </th> 
    </tr> 
    </tbody> 
<!-- the form for saving exactly one movie --> 

<form class="hide" id="movie{{ forloop.counter }}" action="{% url 'myapp:movieDataUpdate' pk=movie.pk %}" method="post"> 
{% csrf_token %} 
</form> 
</table> 

这是我现有的视图/网址/形式各行上保存按钮:

urls.py

from django.conf.urls import url 
from . import views 

app_name = "myapp" 
urlpatterns = [ 
     url(r'^$', views.AllMovies.as_view(), name="index"), views.UpdateMovieDataView.as_view(), name='movieDataUpdate'), 
] 

views.py

class UpdateMovieDataView(UpdateView): 
    model = Movie 
    form_class = UpdateMovieDataForm 
    success_url = reverse_lazy('myapp:index') 

    def form_valid(self, form): 
     self.object.slug = slugify(form.cleaned_data['title']) 
     return super(UpdateMovieDataView, self).form_valid(form) 

forms.py

class UpdateMovieDataForm(forms.ModelForm): 
     class Meta: 
      model = Movie 
      fields = ['title', 'date', 'director', 'runtime', 'genre', 'status'] 

我希望有人能帮助我,试图弄明白,但还没有成功。也许有更多经验的人可以帮助:)

回答

1

你可以在其上添加javascript(jQuery很容易启动)。

您首先将jQuery添加到您的html页面(download here)。

然后添加一个ID你的复选框(如下所示):

<input id="my_checkbox1" type="checkbox" class="custom-control-input"> 

,然后添加JavaScript代码(在HTML),其检测复选框变化,并作出AJAX到你的服务器。

<script> 
$("#my_checkbox1").change(function() { 
    if(this.checked) { 
     $.post("{% url 'myapp:movieDataUpdate' pk=movie.pk %}", {}, 
     function(data, status){ 
      console.log("Data: " + data + "\nStatus: " + status); 
     }); 
    } 
    # If you want, make an else 
}); 
</script> 

这里使用的一些来源:

jQuery checkbox checked state changed event

https://www.w3schools.com/jquery/jquery_ajax_get_post.asp

+0

我不明白你想要这个复选框上的改变,或按钮保存点击。但是,如果你想按钮点击,而不是复选框上的AJAX更改,只需将其添加到列表中,并且当您单击时,您将提交(或AJAX)的更改。 – Rafael