如何从Django DeleteView发送错误消息?

时间:2019-01-31 18:29:01

标签: django django-views django-class-based-views

假设有两个模型ParentChildParentchild是一对多的关系。

我正在为Parent模型创建DeleteView。在删除之前,我需要检查是否Parent {具有{1}}。如果没有Children,则Children模型被删除像往常一样。但是如果有Parent,那么我需要向DeleteView确认页面发送错误消息。

如何使用DeleteView实现此目的?

2 个答案:

答案 0 :(得分:1)

您可以覆盖delete方法并使用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)  

答案 1 :(得分:1)

DeleteView继承了DeletionMixin。你可以做的就是添加on_delete=PROTECTED在您的孩子模型和覆盖delete方法在您的视图赶上ProtectedError例外。有关错误消息,请参见Django的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)