This is a Django mixin that allows ModelAdmin classes to execute actions without selecting any objects on the change list of the Django Admin.
To implement it you need to include the Mixin as usual (see https://docs.djangoproject.com/en/1.10/topics/class-based-views/mixins/)
and define a class attribute called extended_actions
containing a list of string with the name of the actions that you want to be exectued
with empty queryset.
If in the action you want to use the same queryset that the user is seeing, you can use the get_filtered_queryset
method also provided by the mixin
@admin.register(Contact)
class ContactAdmin(ExtendedActionsMixin, admin.ModelAdmin):
list_display = ('name', 'country', 'state')
actions = ('export',)
extended_actions = ('export',)
def export(self, request, queryset):
if not queryset:
# if not queryset use the queryset filtered by the URL parameters
queryset = self.get_filtered_queryset(request)
# As usual do something with the queryset
Thank you for supplying this snippet. One question though: why even bother implementing
get_changelist_instance
here? It leaves out the checkboxes, so regular actions are rendered useless. After removing it, the mixin just works for both classic actions and the 'extended' ones (as expected). Python 3.8.11 Django 3.2.6.