处理Django DeleteView中的PROTECT ERROR [英] Handle PROTECT ERROR in Django DeleteView

查看:165
本文介绍了处理Django DeleteView中的PROTECT ERROR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django DeleteView 删除数据库中的项目。我使用了单独的模板来显示删除确认消息,但是当我按是按钮时,由于客户表与帐户表链接,因此得到 ProtectedError 。因此,我想处理 ProtectedError 并在同一模板中向用户提供另一条消息。

I am using Django DeleteView to delete items in my database. I have use separate template to show the delete confirmation message, but when I press the yes button I get ProtectedError since customer table is linked with Accounts table. Hence I want to handle the ProtectedError and give user another message in the same template.

这是我的代码曾经执行过删除操作:

Here is the code I have used to perform the delete:

class Customer(DeleteView):
    #Delete Customers
    model = Customer
    template_name = 'project_templates/delete_customer.html'

    def get_success_url(self):
        return reverse('inactive_customers')

如果有人可以向我建议一种处理这种情况的方法,那真是太好了。

It would be really great if someone can suggest me a method to handle this situation.

推荐答案

您应该能够捕获该异常。当您查看 DeletionMixin

You should be able to catch the exception. When you look at the DeletionMixin:

https://github.com/django/django/blob/master/django/views/generic/edit.py# L256

您可以覆盖 post 方法并实现以下操作:

You can override the post method and achieve something like:

def post(self, request, *args, **kwargs):
    try:
        return self.delete(request, *args, **kwargs)
    except ProtectedError:
        # render the template with your message in the context
        # or you can use the messages framework to send the message

希望这会有所帮助。

这篇关于处理Django DeleteView中的PROTECT ERROR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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