[Answered ]-Get values from checkboxes in django

1👍

Since a delete removes items, you need to do this through a POST or DELETE request, not a GET request.

A DeleteView does not delete items in bulk, it is implemented to delete a single object. We thus have to implement our own view:

from django.http import HttpResponseRedirect
from django.views.generic.edit import DeletionMixin

class PDeleteBulkView(DeletionMixin, TemplateView):
    template_name='kammem/delete.html'
    model=Person
    success_url=reverse_lazy('personer')

    def delete(self, *args, **kwargs):
        success_url = self.get_success_url()
        Person.objects.filter(
            pk__in=self.request.POST.getlist('checks')
        ).delete()
        return return HttpResponseRedirect(success_url)

In the HTML form, you thus should make a POST request to the PDeleteView:

<form method="POST" action="{% URL 'name-of-pdelete-bulk-view' %}">
    … table …
    <button type="submit">delete</button>
</form>

here the checkboxes will thus, if checked add data to the checks item. If you then click the delete button, you will make a POST request to the PDeleteBulkView that will remove the items in bulk.

Note that we here do not check any permissions, we thus assume that the user can delete these items. Furthermore we do not check if the primary keys are all items that "belong" to the user, a user can thus fabricate a POST request and remove other items. You will thus need to add security, for example by filtering the queryset such that only items for which the user is the "owner" can be removed.

Leave a comment