问题描述
比方说,有两种模型 Parent
和 Child
.将父级
赋予 child
是一对多的关系.
Let's say there are two models Parent
and Child
. Parent
to child
is one to many relationship.
我正在为Parent模型创建DeleteView.删除之前,我需要检查 Parent
是否具有 Children
.如果没有 Children
,则照常删除 Parent
模型.但是,如果有 Children
,那么我需要向DeleteView确认页面发送错误消息.
I am creating DeleteView for Parent model. Before deleting I need to check whether Parent
has Children
. If there are no Children
then Parent
model is deleted as usual. But if there are Children
then I need to send error message to DeleteView confirmation page.
如何使用DeleteView实现此目的?
How can I achieve this using DeleteView?
推荐答案
DeleteView继承了 DeletionMixin .您可以做的是在子模型中添加 on_delete = PROTECTED
,并在视图中覆盖delete方法以捕获 ProtectedError
异常.有关错误消息,请参见Django的消息框架.
DeleteView inherites the DeletionMixin. What you can do is add on_delete=PROTECTED
in your child model and override the delete method in your view to catch a ProtectedError
exception. For the error message, see Django's message framework.
models.py:
models.py:
class Child():
#...
myParent = models.ForeignKey(Parent, on_delete=PROTECTED)
views.py:
from django.db.models import ProtectedError
#...
class ParentDelete(DeleteView):
#...
def delete(self, request, *args, **kwargs):
"""
Call the delete() method on the fetched object and then redirect to the
success URL. If the object is protected, send an error message.
"""
self.object = self.get_object()
success_url = self.get_success_url()
try:
self.object.delete()
except ProtectedError:
messages.add_message(request, messages.ERROR, 'Can not delete: this parent has a child!')
return # The url of the delete view (or whatever you want)
return HttpResponseRedirect(success_url)
这篇关于如何从Django DeleteView发送错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!