[Django]-Setting Django admin default action

2đź‘Ť

1.Override the get_action_choices() method in your ModelAdmin, clear the default blank choice and reorder the list。

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.Specific action.Override ModelAdmin.changelist_view, use extra_context to update action_form

ChoiceField.initial used to set the default selected choice.
so if your action name is “print_it”, you can do this.

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)
👤xavierskip

1đź‘Ť

in your admin.py file

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

and in your class

class TestCaseAdmin(MyModelAdmin):
👤Nils Zenker

0đź‘Ť

I think you can override the get_action_choices() method in the 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
👤Rod Xavier

Leave a comment