How to add a cancel button to DeleteView in django

Your approach of overriding the post method and checking to see if the cancel button was pressed is ok. You can redirect by returning an HttpResponseRedirect instance.

from django.http import HttpResponseRedirect

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')

    def post(self, request, *args, **kwargs):
        if "cancel" in request.POST:
            url = self.get_success_url()
            return HttpResponseRedirect(url)
        else:
            return super(AuthorDelete, self).post(request, *args, **kwargs)

I've used get_success_url() to be generic, its default implementation is to return self.success_url.


Why don't you simply put a "Cancel" link to the success_url instead of a button? You can always style it with CSS to make it look like a button.

This has the advantage of not using the POST form for simple redirection, which can confuse search engines and breaks the Web model. Also, you don't need to modify the Python code.