[Django]-How to send error message from Django DeleteView?

3👍

DeleteView inherites the DeletionMixin. What you can do is add on_delete=PROTECTED in your child model and override the delete method in your view to catch a ProtectedError exception. For the error message, see Django’s message framework.

models.py:

class Child():
    #...
    myParent = models.ForeignKey(Parent, on_delete=PROTECTED)

views.py:

from django.db.models import ProtectedError

#...

class ParentDelete(DeleteView):
    #...
    def delete(self, request, *args, **kwargs):
        """
        Call the delete() method on the fetched object and then redirect to the
        success URL. If the object is protected, send an error message.
        """
        self.object = self.get_object()
        success_url = self.get_success_url()

        try:
            self.object.delete()
        except ProtectedError:
            messages.add_message(request, messages.ERROR, 'Can not delete: this parent has a child!')
            return # The url of the delete view (or whatever you want)

        return HttpResponseRedirect(success_url)
👤Andy

1👍

You could override delete method and set a message using Django’s message framework

from django.contrib import messages

class DeletePArent(DeleteView):

   # ...

   def delete(self, request, *args, **args):
       object = self.get_object()
       if object.chidlren.count() > 0:
           messages.add_message(request, messages.ERROR, "Can't be deleted, has childern")
           return redirect('url-of-your-choice')
       return super().delete(request, *args, **kwargs)  

Leave a comment