[Django]-Django admin: can I define fields order?

78šŸ‘

āœ…

You can order the fields as you wish using the ModelAdmin.fields option.

class GenreAdmin(admin.ModelAdmin):
    fields = ('title', 'parent')
šŸ‘¤Alasdair

9šŸ‘

Building off rbennellā€™s answer I used a slightly different approach using the new get_fields method introduced in Django 1.7. Here Iā€™ve overridden it (the code would be in the definition of the parentā€™s ModelAdmin) and removed and re-appended the ā€œparentā€ field to the end of the list, so it will appear on the bottom of the screen. Using .insert(0,ā€™parentā€™) would put it at the front of the list (which should be obvious if youā€™re familiar with python lists).

def get_fields (self, request, obj=None, **kwargs):
    fields = super().get_fields(request, obj, **kwargs)
    fields.remove('parent')
    fields.append('parent') #can also use insert
    return fields

This assumes that your fields are a list, to be honest Iā€™m not sure if thatā€™s an okay assumption, but itā€™s worked fine for me so far.

šŸ‘¤thrillhouse

6šŸ‘

I know itā€™s an old question, but wanted to thow in my two cents, since my use case was exactly like this, but i had lots of models inheriting from one class, so didnā€™t want to write out fields for every admin. Instead I extended the get_form model and rearranged the fields to ensure parent always comes at the end of the fields in the admin panel for add/change view.

class BaseAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(BaseAdmin, self).get_form(request, obj, **kwargs)
        parent = form.base_fields.pop('parent')
        form.base_fields['parent '] = parent 
        return form

base_fields is an OrderedDict, so this appends the ā€˜parentā€™ key to the end.
Then, extend this admin for any classes where you want parent to appear at the end:

class GenreAdmin(BaseAdmin):
    pass
šŸ‘¤rbennell

1šŸ‘

This simple solution from @acquayefrank (in the comments) worked for me:

The order of fields would depend on the order in which you declare them in your models.

šŸ‘¤Arnaud P

Leave a comment