假设有两个模型Parent
and Child
. Parent
to child
是一对多的关系。
我正在为父模型创建DeleteView。在删除之前我需要检查是否Parent
has Children
。如果没有Children
then Parent
模型照常删除。但如果有Children
然后我需要将错误消息发送到DeleteView确认页面。
我如何使用DeleteView 来实现这一点?
DeleteView继承了删除混合 https://docs.djangoproject.com/en/2.1/ref/class-based-views/mixins-editing/#django.views.generic.edit.DeletionMixin。你能做的就是添加on_delete=PROTECTED
在您的子模型中并覆盖视图中的删除方法以捕获ProtectedError
例外。有关错误消息,请参阅 Django 的消息框架 https://docs.djangoproject.com/en/2.1/ref/contrib/messages/.
模型.py:
class Child():
#...
myParent = models.ForeignKey(Parent, on_delete=PROTECTED)
视图.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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)