On Django's admin pages, I'd like to perform an action when the administrator clicks the Delete button for an object. In other words, I'd like to execute some code prior to arriving on the "Are you sure?" delete confirmation page.
I realize I could override the template page for this object, but I was hoping for something easier (i.e., override a method on the model or the form).
Any thoughts?
You can override ModelAdmin.delete_view()
method, like:
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)
We can use django.shortcuts.redirect to interrupt deletion, like this:
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('..')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With