Django - User full name as unicode

自古美人都是妖i 提交于 2019-12-03 13:07:24
Francis Yaconiello

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 

If you have a profile model set up as Django suggests, you could define the full name on that model

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    ...

@property
def full_name(self):
    return "%s %s" % (self.user.first_name, self.user.last_name)

then anywhere you have access to the user object you can easily do user.get_profile.full_name

Alternatively, if you only need the full name in the template you could write a simple tag:

@register.simple_tag
def fullname(user):
    return "%s %s" % (user.first_name, user.last_name)

Just slam get_full_name to the __unicode__ method like so

User.__unicode__ = User.get_full_name

Make sure you override it with the callable, not the result of the function. User.get_full_name() will fail with the open and close brackets.

Place on any included file and you should be good.

I found there's a quick way to do this in Django 1.5. Check this: custom User models

and I also notice,

User.__unicode__ = User.get_full_name()

which metions by Francis Yaconiello is not work on my side (Django 1.3). Will raise error like this:

TypeError: unbound method get_full_name() must be called with User instance as first argument (got nothing instead)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!