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']
其他方法非常受欢迎。
推荐阅读
- python-3.x - Visual Studio Code:在 python 中突出显示的导入
- collections - 无法在 Postman 中使用变量命中端点
- java - 如何强制 Testcontainers 使用特定的 docker 镜像?
- python - 如何根据列表中的元素之一对给定的python字典进行排序,并将列表作为值?
- javascript - VueJS:绑定一个具有 3 个潜在值的变量?
- awk - 列中的 Linux 单词以“a”结尾
- python - 在 Python 中读取 json
- ios - 如何在 Swift 中替换多元素 NSArray 的单个变量
- node.js - NodeJS/Express 为 PDF 返回设置浏览器标题
- django - 如何在 Django 分页中将 ?page=1 重定向到 /?