Django - User full name as unicode

Pierre de LESPINAY picture Pierre de LESPINAY · Aug 10, 2012 · Viewed 18k times · Source

I have many Models linked to User and I'd like my templates to always display his full_name if available. Is there a way to change the default User __unicode__() ? Or is there another way to do it ?

I have a profile model registered where I can define the __unicode__(), should I link all my models to it ? Seems not a good idea to me.


Imagine I need to display the form for this object

class UserBagde
    user = model.ForeignKey(User)
    badge = models.ForeignKey(Bagde)

I will have to select box with __unicodes__ of each object, won't I ?
How can I have full names in the user's one ?

Answer

Francis Yaconiello picture Francis Yaconiello · Aug 10, 2012

Try this:

User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name))

EDIT

Apparently what you want already exists..

https://docs.djangoproject.com/en/dev/ref/contrib/auth/#django.contrib.auth.models.User.get_full_name

ALSO

if its imperative that the unicode function be replaced:

def user_new_unicode(self):
    return self.get_full_name()

# Replace the __unicode__ method in the User class with out new implementation
User.__unicode__ = user_new_unicode 

# or maybe even
User.__unicode__ = User.get_full_name()

Fallback if name fields are empty

def user_new_unicode(self):
    return self.username if self.get_full_name() == "" else self.get_full_name()

# Replace the __unicode__ method in the User class with out new implementation
User.__unicode__ = user_new_unicode