设置Django管理默认操作

3

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


@solarissmoke:那不一样。我想要在管理员操作中。 - d33tah
您只需要覆盖相应的管理表单,就可以应用相同的概念。 - solarissmoke
3个回答

2

1. 在您的 ModelAdmin 中覆盖 get_action_choices() 方法,清除默认的空白选项并重新排列列表。

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)

选择 = super(MyModelAdmin,self).get_action_choices(request) - Nils Zenker
@NilsZenker 好的,我会修复它。 - xavierskip

1

在你的 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):

0

我认为你可以在ModelAdmin中重写get_action_choices()方法。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接