0

I've got a project with quite a few admin-actions. Currently I'm registering them like so:

@admin.action(description='Some admin action description')
def do_something_action(self, request, queryset):
    pass

Some of these are being added to the admin-class of another app so I cannot simply add the function directly on the class where they are needed.

The problem is that these actions are shown project-wide, on every admin-screen. How can I stop this behaviour, and manually set them where they are wanted? If it matters, it's Django3.2.

S.D.
  • 2,486
  • 1
  • 16
  • 23

1 Answers1

0

As I couldn't find out why these actions are shown project wide, I decided to manually override the get_actions function.

Firstly, a Mixin was created to deal with the exclusion of certain actions.

class ExcludedActionsMixin:
    '''
    Exclude admin-actions. On the admin, you're expected to have
    excluded_actions = [...]

    Keep in mind that this breaks the auto-discovery of actions. 
    You will need to set the ones you actually want, manually.
    '''

    def get_actions(self, request):
        # We want to exclude some actions from this admin.  Django seems to auto assign all general actions
        # that aren't included in the class by default to the entire package.  But we have some actions
        # intended for another package here. This wouldn't work.
        actions = super().get_actions(request)
        # so let's recompile the actions list and keeping excluded_actions in mind.
        for excluded_action in self.excluded_actions:
            try:
                del actions[excluded_action]
            except KeyError:
                pass
        return actions

This Mixin is used to do both local overrides in specific apps, but also to create a 'default' admin which contains the most wanted

class DefaultAdminActions(ExcludedActionsMixin, admin.ModelAdmin):
    # There are a number of actions we want to be excluded pretty much everywhere.  Instead of
    # setting them again and again, we'll just delcare them here.
    # And import DefaultAdmin instead of admin.ModelAdmin
    excluded_actions = ['unwanted_action1', 'unwanted_action2', 'unwanted_action3']

Other approaches are more than welcome.

S.D.
  • 2,486
  • 1
  • 16
  • 23