- October 23, 2015
- admin wrap delete_selected
- 2 (after 2 ratings)
The idea here is to wrap the original
delete_selected functionality in a way that I shouldn't have to reimplement the templates (confirmation/error response) serving, just extend the original.
What this code does, it wraps the queryset's delete function with a closure, so when it really gets called (after the confirmation), it executes the extra functionality you wish to.
After looking at the original code, this seemed to be the most efficient way of doing it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
from django.contrib.admin.actions import delete_selected class YourModelAdmin(admin.ModelAdmin): def my_delete_selected(self, modeladmin, request, queryset): delete_orig = queryset.delete def _delete_closure(): """ The idea here is to wrap the original delete (gets called by delete_selected() when it does the actual deletion. """ result = delete_orig() your_extra_functionality(request) return result queryset.delete = _delete_closure return delete_selected(modeladmin, request, queryset) def get_actions(self, request): 'Patch delete_selected to have our version running' actions = super(YourModelAdmin, self).get_actions(request) actions['delete_selected'] = ( self.my_delete_selected, 'delete_selected', delete_selected.short_description) return actions