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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 4 weeks, 1 day ago
  2. Python Django CRUD Example Tutorial by tuts_station 1 month, 2 weeks ago
  3. Browser-native date input field by kytta 2 months, 4 weeks ago
  4. Generate and render HTML Table by LLyaudet 3 months, 1 week ago
  5. My firs Snippets by GutemaG 3 months, 1 week ago

Comments

Please login first before commenting.