我想构建一个包含多个具有复选框的项目的表,如果选中了这些复选框,我想通过按钮单击更新这些项目。
我已经有了一个更新视图来执行此操作,但仅适用于一个项目,并且仅当按下此项目的保存按钮时(每个表项都有它自己的按钮)。我的代码如下所示:
<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']
我希望有人能在这里帮助我,试图弄明白,但还没有成功。也许拥有更多经验的人可以提供帮助:)
答案 0 :(得分: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>
这里使用了一些来源: