Login

Smart wrapping Django admin's delete_selected

Author:
karolyi
Posted:
October 23, 2015
Language:
Python
Version:
1.7
Score:
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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.