Display full names in django form, not username

django, django-forms

Solution

Not absolutely sure the following works if you have a regular ChoiceField but if you have a modelChoiceField you can do the following:

class UserModelChoiceField(forms.ModelChoiceField):
    """
    Extend ModelChoiceField for users so that the choices are
    listed as 'first_name last_name (username)' instead of just
    'username'.

    """
    def label_from_instance(self, obj):
        return "%s (%s)" % (obj.get_full_name(), obj.username)


class XYZForm(forms.Form):
    ...
    xyz = UserModelChoiceField(User.objects.all())

Problem

I have a Django app that has activities and objects that have foreign keys to the User object that is defined in django.contrib.auth.models. In doing this, I get the `username` property of the user, which is the login id. Since the User object stores the full name, how do I make a ChoiceField on an form display the full names of the user, not the username, but still link it back to the correct User object after the form is Posted?

Original source