Search code examples
djangoviewdelete-row

Deleting multiple rows in Django frontend


I am going to implment a multi delete (via select boxes) view in django.

I know there's a view in django.contrib.admin.actions but I can't port this to frontend.

Should I assign object id's in the form and POST these to my delete view and then use .delete() ?

I haven't been programming before, and Django is the framework I start my programming adventure.

I was looking for example (for Django view + html) but couldn't find any.


Solution

  • Using a modelformset and manually rendering the form with just the delete options: https://docs.djangoproject.com/en/dev/topics/forms/formsets/#manually-rendered-can-delete-and-can-order

    Alternative solution:

    Using a modelformset to create a bunch of forms with a delete checkbox like this:

    class YourModelForm(forms.ModelForm):
        id = fields.IntegerField(widget=widgets.HiddenInputField)
        delete = fields.BooleanField(required=False)
    
        def save(self, commit=False):
            if self.is_valid() and self.cleaned_data['delete']:
                self.instance.delete()             
    
        class Meta:
            model = YourModel