问题
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