处理 Django DeleteView 中的保护错误

PIK*_*IKP 2 django django-forms django-generic-views django-class-based-views

我正在使用 DjangoDeleteView删除我的数据库中的项目。我使用单独的模板来显示删除确认消息,但是当我按下是按钮时,我得到了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')
Run Code Online (Sandbox Code Playgroud)

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

jbu*_*bub 5

您应该能够捕获异常。当您查看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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 记得导入:`from django.db.models import ProtectedError` (4认同)