Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Delete button to django.forms generated form?

Tags:

python

django

How to add a Delete button to django.forms generated edit form (note, NOT admin)?

Its very easy to add a delete view on (/app/model/<id>/delete/ etc) but how to add a "Delete" button alongside the generated form?

I've got to be missing something easy?

like image 400
Ryan Avatar asked Mar 01 '11 21:03

Ryan


2 Answers

Add a submit button to the template, set the name as 'delete', check in your view if it was clicked:

if request.POST.get('delete'):
    obj.delete()
like image 118
zsquare Avatar answered Nov 05 '22 05:11

zsquare


You could use some generic form like this

class DeletableModelForm(forms.ModelForm):
    """
    Model form that allows you to delete the object
    """
    delete = forms.BooleanField(
        initial=False,
        help_text=_('Check this to delete this object')
    )

    def save(self, commit=True):
        if self.cleaned_data['delete']:
            return self.instance.delete()
        return super(DeletableModelForm, self).save()

And then you could restyle the checkbox to look like button. But you are probably better of with normal button with name...

like image 40
Visgean Skeloru Avatar answered Nov 05 '22 05:11

Visgean Skeloru