Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send error message from Django DeleteView?

Let's say there are two models Parent and Child. Parent to child is one to many relationship.

I am creating DeleteView for Parent model. Before deleting I need to check whether Parent has Children. If there are no Children then Parent model is deleted as usual. But if there are Children then I need to send error message to DeleteView confirmation page.

How can I achieve this using DeleteView?

like image 985
Pavan Kumar Avatar asked Jun 20 '26 05:06

Pavan Kumar


1 Answers

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)
like image 96
Andy Avatar answered Jun 22 '26 00:06

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!