Django多模型复用自定义admin action时如何动态修改显示名称
Django Admin 复用自定义Action并为不同模型设置不同显示名称的实现方案
这里分两种常用的实现方式,都不需要重复编写业务逻辑代码:
方案1:使用Action工厂函数(适合单个Action复用场景)
通过高阶函数动态生成带自定义描述的Action实例,原有业务逻辑只需要写一次:
# 定义Action工厂函数,接收自定义显示名称作为参数 def get_custom_action(description): def custom_action(request, modelAdmin, queryset): # 原有业务逻辑保持不变 # do something here return response # 为生成的Action设置传入的显示名称 custom_action.short_description = description return custom_action # 不同Admin类调用工厂函数传入对应名称即可 class MyXAdmin(admin.ModelAdmin): actions = [get_custom_action('My custom action for X')] class MyYAdmin(admin.ModelAdmin): actions = [get_custom_action('My custom action for Y')]
方案2:使用Mixin基类(适合多个通用配置/Action复用场景)
如果需要复用的不止一个Action,或者还有其他通用Admin配置,可以用Mixin类实现,扩展性更强:
# 定义通用Action的Mixin基类 class CustomActionMixin: # 预留自定义名称的类属性,子类可以覆盖 custom_action_desc = "默认操作名称" def custom_action(self, request, queryset): # 原有业务逻辑保持不变 # do something here return response def get_actions(self, request): actions = super().get_actions(request) # 动态修改Action的显示名称 if 'custom_action' in actions: actions['custom_action'][0].short_description = self.custom_action_desc return actions # 不同Admin类继承Mixin,覆盖自定义名称属性即可 class MyXAdmin(CustomActionMixin, admin.ModelAdmin): custom_action_desc = 'My custom action for X' actions = ['custom_action'] class MyYAdmin(CustomActionMixin, admin.ModelAdmin): custom_action_desc = 'My custom action for Y' actions = ['custom_action']
内容的提问来源于stack exchange,提问作者Tanvir Nayem
相关产品推荐
相关产品推荐

