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

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


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


When working with a ModelForm, I found the following most useful so that I didn't have to redefine my queryset - in particular because I used limit_choices_to in the model definition:

class MyModelForm(forms.ModelForm):    def __init__(self, *args, **kwargs):        super(MyModelForm, self).__init__(*args, **kwargs)        self.fields['user'].label_from_instance = lambda obj: "%s" % obj.get_full_name()

customised from this answer https://stackoverflow.com/a/7805824/432992


You can override the field with a custom ModelChoiceField and change the label_from_instance function to return get_full_name instead. See the docs for ModelChoiceField: http://docs.djangoproject.com/en/1.2/ref/forms/fields/#modelchoicefield