【问题标题】:Handle PROTECT ERROR in Django DeleteView在 Django DeleteView 中处理 PROTECT ERROR
【发布时间】:2013-11-15 12:42:51
【问题描述】:

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

这是我用来执行删除的代码:

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

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

如果有人能建议我一种处理这种情况的方法,那就太好了。

【问题讨论】:

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


    【解决方案1】:

    您应该能够捕捉到异常。当你看DeletionMixin:

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

    您可以覆盖post 方法并实现类似:

    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
    

    希望这会有所帮助。

    【讨论】:

    • 记得导入:from django.db.models import ProtectedError
    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2011-07-28
    • 2021-07-23
    相关资源
    最近更新 更多