Django - 用户全名为unicode

Pie*_*NAY 8 python django django-models django-users

我有许多模型链接到User,我希望我的模板总是显示他的full_name(如果可用).有没有办法改变默认值User __unicode__()?或者还有另一种方法吗?

我有一个可以定义的配置文件模型,我__unicode__()应该将所有模型链接到它吗?对我来说似乎不是一个好主意.


想象一下,我需要显示这个对象的表单

class UserBagde
    user = model.ForeignKey(User)
    badge = models.ForeignKey(Bagde)
Run Code Online (Sandbox Code Playgroud)

我将不得不选择__unicodes__每个对象的盒子,不是吗?
如何在用户名中使用全名?

Fra*_*llo 20

试试这个:

User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name))
Run Code Online (Sandbox Code Playgroud)

编辑

显然你想要的已经存在..

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

如果必须更换unicode功能:

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()
Run Code Online (Sandbox Code Playgroud)

如果名称字段为空,则回退

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 
Run Code Online (Sandbox Code Playgroud)