I have a model that has a ForeignKey to the built-in user model in django.contrib.auth and I’m frustrated by the fact the select box in the admin always sorts by the user’s primary key.
I’d much rather have it sort by username alphabetically, and while it’s my instinct not to want to fiddle with the innards of Django, I can’t seem to find a simpler way to reorder the users.
The most straightforward way I can think of would be to dip into my Django install and add
ordering = ('username',)
to the Meta class of the User model.
Is there some kind of monkeypatching that I could do or any other less invasive way to modify the ordering of the User model?
Alternatively, can anyone thing of anything that could break by making this change?
There is a way using ModelAdmin objects to specify your own form. By specifying your own form, you have complete control over the form’s composition and validation.
Say that the model which has an FK to
UserisFoo.Your
myapp/models.pymight look like this:You would then create a
myapp/admin.pyfile containing something like this:Once you’ve done this, the
<select>dropdown will order the user objects according to username. No need to worry about to other fields onFoo… you only need to specify the overrides in yourFooAdminFormclass. Unfortunately, you’ll need to provide this custom form definition for every model having an FK to User that you wish to present in the admin site.