由于我无法找出为什么这些操作会在项目范围内显示,因此我决定手动覆盖该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']
其他方法非常受欢迎。