2017-04-06 100 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