问题描述
@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']
非常欢迎其他方法。