Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Django ModelChoiceField to show users' full names rather than usernames

I have a form in my Django app (not in admin) that allows staff members to select a user from a dropdown.

forms.ModelChoiceField(queryset = User.objects.filter(is_staff=False), required = False) 

The problem is that the dropdown shows users by usernames whereas I'd rather it show their full name from user.get_full_name() and use username only if that is not available. I only really need this change on this page, in other places like admin, I don't care if it uses username.

Is there a way I can do this?

Thanks!

like image 294
Adam Avatar asked Jul 02 '10 17:07

Adam


1 Answers

You can setup a custom ModelChoiceField that will return whatever label you'd like.

Place something like this within a fields.py or wherever applicable.

class UserModelChoiceField(ModelChoiceField):     def label_from_instance(self, obj):          return obj.get_full_name() 

Then when creating your form, simply use that field

 UserModelChoiceField(queryset=User.objects.filter(is_staff=False), required = False) 

More info can be found here

like image 156
Bartek Avatar answered Sep 21 '22 19:09

Bartek