如何从Django DeleteView发送错误消息? [英] How to send error message from Django DeleteView?

查看:58
本文介绍了如何从Django DeleteView发送错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,有两种模型 Parent Child .将父级赋予 child 是一对多的关系.

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

我正在为Parent模型创建DeleteView.删除之前,我需要检查 Parent 是否具有 Children .如果没有 Children ,则照常删除 Parent 模型.但是,如果有 Children ,那么我需要向DeleteView确认页面发送错误消息.

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.

如何使用DeleteView实现此目的?

How can I achieve this using DeleteView?

推荐答案

DeleteView继承了消息框架.

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:

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)

这篇关于如何从Django DeleteView发送错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆