首页 > 解决方案 > 阻止 Django 管理操作显示项目范围

问题描述

我有一个包含很多管理操作的项目。目前我正在像这样注册它们:

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

其中一些被添加到另一个应用程序的管理类中,所以我不能简单地将函数直接添加到需要它们的类上。

问题是这些操作在每个管理屏幕上都显示在项目范围内。我怎样才能停止这种行为,并手动将它们设置在需要的位置?如果重要的话,那就是 Django3.2。

标签: djangodjango-admindjango-admin-actions

解决方案


由于我无法找出为什么这些操作会在项目范围内显示,因此我决定手动覆盖该get_actions功能。

首先,创建了一个 Mixin 来处理某些操作的排除。

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

这个 Mixin 用于在特定应用程序中进行本地覆盖,还可以创建一个“默认”管理员,其中包含最想要的

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']

其他方法非常受欢迎。


推荐阅读