设置Django管理员默认操作

时间:2015-11-12 06:57:40

标签: django

我想将名为“---------”(BLANK_CHOICE_DASH)的默认选定操作更改为另一个特定操作。有没有更好的方法来实现这个,而不是添加一些可以在加载时覆盖操作的javascript代码?

3 个答案:

答案 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)

您的admin.py文件中的

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):