3

I would like to change the default selected action named "---------" (BLANK_CHOICE_DASH) to another specific action. Is there a better way to implement this than adding some javascript code that would override the action in load time?

d33tah
  • 10,999
  • 13
  • 68
  • 158

3 Answers3

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
  • 431
  • 4
  • 12
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
  • 3,983
  • 1
  • 29
  • 41
0

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
  • 659
  • 7
  • 11