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']
我希望有人能帮助我,试图弄明白,但还没有成功。也许有更多经验的人可以帮助:)
我不明白你想要这个复选框上的改变,或按钮保存点击。但是,如果你想按钮点击,而不是复选框上的AJAX更改,只需将其添加到列表中,并且当您单击时,您将提交(或AJAX)的更改。 – Rafael