Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display full names in django form, not username

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?

like image 651
Technical Bard Avatar asked Jul 06 '09 06:07

Technical Bard


1 Answers

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())
like image 192
lemonad Avatar answered Nov 15 '22 17:11

lemonad