views:

257

answers:

2

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?

+9  A: 

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())
lemonad
Thanks - exactly what I was looking for...
Technical Bard
A: 

To add to the previous answer, if you are trying to modify a form in the admin then the XYZForm class should inherit from forms.ModelForm and in admin.py you should make a XYZAdmin class with the form attribute = XYZForm

Bjarni