您可以在 Django 中使用FormView 并按如下方式处理它们。您需要先创建一个带有复选框的表单:
# forms.py
class CheckboxesForm(forms.Form):
checkboxes = forms.ModelMultipleChoiceField(
MyModel.objects.all(),
widget=forms.CheckboxSelectMultiple)
然后你需要编写自己的FormView并重写form_valid()方法来执行选中对象的删除。如果要定义具有复选框的对象,可以覆盖 get_form() 方法。
# views.py
class MyListView(ListView):
"""
View displaying a list of objects, you will redirect here after successfully deleting the objects you want
"""
model = MyModel
class MyView(FormView):
"""
Class based view taking care of rendering the form and processing it after posting. Finally, redirects you to your list view defined above.
"""
form_class = MyForm
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['objects'] = MyModel.objects.all() # Customize this queryset to your liking
return context
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields['checkboxes'].queryset =
MyModel.objects.all() # Customize this queryset to determine for which objects you want to display checkboxes
return form
def form_valid(self, form):
qs = myModel.objects.filter(
pk__in=list(map(int, self.request.POST.getlist('checkboxes'))))
qs.delete()
return HttpResponseRedirect(reverse_lazy('someurl'))
您的模板将如下所示(改编自您发布的内容)
# template.html
{% for j in objects %}
<h4>
Select All
<input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" />
</h4>
<button class="btn btn-danger" action=" ">Delete</button>
<div class="col">
{% if i.placename == j.gallery_place %}
<div class="show-image">
<img src="{{j.gallery_image.url}}" style="height:130px;
width:130px;" />
<tag class="one" style="margin:8%">
<div class="form-checkbox"><input type="checkbox" name="checkboxes" value="{{ j.pk }}">
</tag>
</div>
{% endif %}
</div>
{% endfor %}
最后,连接网址。
# urls.py
from django.conf.urls import include, url
from.views import MyView, MyListView
urlpatterns = [
url(r'^listdelete/$', MyView.as_view(), name="delete-list"),
url(r'^mylist/$, MyListView.as_view(), name="someurl"),
]