6

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?

2 Answers 2

17

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I was expecting some way of doing this automagically via forms.py Meta: or similar?
Django forms dont do buttons. Its upto you to put them in the template. There are pluggable apps (django-uni-form) though that will allow you to create forms with buttons in the form definition.
1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.