我想将名为“---------”(BLANK_CHOICE_DASH
)的默认选定操作更改为另一个特定操作。有没有更好的方法来实现这个,而不是添加一些可以在加载时覆盖操作的javascript代码?
答案 0 :(得分:2)
1.在get_action_choices()
中取消ModelAdmin
方法,清除默认空白选项并重新排序列表。
class YourModelAdmin(ModelAdmin):
def get_action_choices(self, request):
choices = super(YourModelAdmin, self).get_action_choices(request)
# choices is a list, just change it.
# the first is the BLANK_CHOICE_DASH
choices.pop(0)
# do something to change the list order
# the first one in list will be default option
choices.reverse()
return choices
2.具体操作。取消ModelAdmin.changelist_view
,使用extra_context
更新action_form
ChoiceField.initial
用于设置默认选择的选项。
因此,如果您的操作名称为" print_it",则可以执行此操作。
class YourModelAdmin(ModelAdmin):
def changelist_view(self,request, **kwargs):
choices = self.get_action_choices(request)
choices.pop(0) # clear default_choices
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = choices
action_form.fields['action'].initial = 'print_it'
extra_context = {'action_form': action_form}
return super(DocumentAdmin, self).changelist_view(request, extra_context)
答案 1 :(得分:0)
我认为您可以覆盖get_action_choices()
中的ModelAdmin
方法。
class MyModelAdmin(admin.ModelAdmin):
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in six.itervalues(self.get_actions(request)):
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
答案 2 :(得分:0)
class MyModelAdmin(admin.ModelAdmin):
def get_action_choices(self, request, **kwargs):
choices = super(MyModelAdmin, self).get_action_choices(request)
# choices is a list, just change it.
# the first is the BLANK_CHOICE_DASH
choices.pop(0)
# do something to change the list order
# the first one in list will be default option
choices.reverse()
return choices
并在你的班级
class TestCaseAdmin(MyModelAdmin):