Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override the method used to call Django's admin delete confirmation page?

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?

like image 955
Huuuze Avatar asked Jun 18 '09 20:06

Huuuze


2 Answers

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)
like image 96
zgoda Avatar answered Sep 22 '22 11:09

zgoda


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('..')
like image 32
bagheera Avatar answered Sep 18 '22 11:09

bagheera