django - 在 Django DeleteView 中处理 PROTECT ERROR

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

我正在使用 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')

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

最佳答案

您应该能够捕捉到异常。当您查看 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

希望这对您有所帮助。

关于django - 在 Django DeleteView 中处理 PROTECT ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775483/

相关文章:

python - 我可以从 Django 模板访问字典中的特定键值吗?

python - 使用 Django 表单编辑图像字段

django - NGINX 有时会出现(没有这样的文件或目录)错误

带有自引用对象的 Django 休息框架嵌套序列化器

python - django 模板中不显示表单字段,仅显示提交按钮

django - 覆盖 Django 1.6 中的 ModelForm 字段错误消息

django基于类的 View -UpdateView-在处理表单时如何访问请求用户?

jquery - 将 django-dynamic-formset 与来自 d​​jango-extra-views 的 CreateWithInlinesView 一起使用 - 多个表单集

python - 尝试允许用户编辑自己的文章——Django