Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change display text in django admin foreignkey dropdown

I have a task list, with ability to assign users. So I have foreignkey to User model in the database. However, the default display is username in the dropdown menu, I would like to display full name (first last) instead of the username. If the foreignkey is pointing to one of my own classes, I can just change the str function in the model, but User is a django authentication model, so I can't easily change it directly right?

Anyone have any idea how to accomplish this?

Thanks a lot!

like image 249
FurtiveFelon Avatar asked Sep 13 '25 15:09

FurtiveFelon


1 Answers

You can create a new ModelForm for your Task model, which will display the list of users however you like (code here assumes a model named Task with a 'user' attribute):

def get_user_full_name_choices:
    return [(user, user.get_full_name()) for user in User.objects.all()]

class TaskAdminForm(forms.ModelForm):
    class Meta:
        model = Task
    user = forms.ChoiceField(choices=get_user_full_name_choices)

Then, tell your ModelAdmin class to use the new form:

class TaskAdmin(admin.ModelAdmin):
    form = TaskAdminForm
like image 126
Chris Lawlor Avatar answered Sep 16 '25 08:09

Chris Lawlor