在Django的管理页面上,我想在管理员单击对象的“删除”按钮时执行操作。换句话说,我想在到达“你确定吗?”之前执行一些代码。删除确认页面。
我意识到我可以覆盖此对象的模板页面,但我希望更容易(例如,覆盖模型或表单上的方法)。
有什么想法吗?
答案 0 :(得分:7)
您可以覆盖ModelAdmin.delete_view()
方法,例如:
class MyModelAdmin(ModelAdmin):
def delete_view(self, request, object_id, extra_context=None):
# if request.POST is set, the user already confirmed deletion
if not request.POST:
perform_my_action()
super(MyModelAdmin, self).delete_view(request, object_id, extra_context)
答案 1 :(得分:3)
我们可以使用django.shortcuts.redirect来中断删除,如下所示:
def check_del(self, object_id):
produkt = Produkt.objects.get(id = object_id)
if produkt.typsklepu_set.all():
return False
else:
return True
def delete_view(self, request, object_id, extra_context=None):
# if request.POST is set, the user already confirmed deletion
if not request.POST and self.check_del(object_id):
return super(ProduktAdmin, self).delete_view(request, object_id, extra_context)
elif request.POST:
return super(ProduktAdmin, self).delete_view(request, object_id, extra_context)
else:
msg = u'Can not delete this object.'
messages.error(request, msg)
return redirect('..')