微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

阻止 Django 管理操作在项目范围内显示

如何解决阻止 Django 管理操作在项目范围内显示

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

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

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

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

解决方法

由于我不知道为什么在项目范围内显示这些操作,我决定手动覆盖 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']

非常欢迎其他方法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。