Handle PROTECT ERROR in Django DeleteView

感情迁移 提交于 2019-12-06 10:29:41

问题


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.


回答1:


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

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

Hope this helps.



来源:https://stackoverflow.com/questions/19775483/handle-protect-error-in-django-deleteview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!