【问题标题】:Django - User full name as unicodeDjango - 用户全名作为 unicode
【发布时间】:2012-08-07 18:59:04
【问题描述】:

我有许多模型链接到User,我希望我的模板始终显示他的全名(如果有)。有没有办法改变默认的 User __unicode__() ?或者有其他方法吗?

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


假设我需要显示这个对象的表单

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

我必须选择每个对象的 __unicodes__ 框,不是吗?
我怎样才能在用户的名字中有全名?

【问题讨论】:

  • 还要记住 first_name 和 last_name 是 User 中的可选字段。所以如果你采用这种方法,你的选择框的某些元素可能没有文本!
  • 这就是为什么我说“如果可用”意味着如果没有则回退到默认值

标签: python django django-models django-users


【解决方案1】:

如果您有一个配置文件模型set up as Django suggests,您可以在该模型上定义全名

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)

然后,您可以在任何可以访问user 对象的地方轻松地访问user.get_profile.full_name

或者,如果您只需要模板中的全名,您可以写一个simple tag:

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

【讨论】:

  • 当我可以直接访问用户对象时(正如我所说我已经有一个配置文件模型),这就是我已经在做的事情,但是例如在我必须从用户中选择的表单中列表,我会一直显示用户名
【解决方案2】:

试试这个:

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

编辑

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

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()

名称字段为空时的回退

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 

【讨论】:

  • 这就是我要搜索的内容。有没有什么地方我可以把这个任务放在任何地方?
  • 把它放在任何已安装应用程序的 models.py 中,我通常有一个会员应用程序,它有我的个人资料模型,我会把它放在那个声明下,但这比任何东西都更个人喜好。
  • 我同意配置文件的位置,我会的,谢谢。实际上,即使我不导入配置文件模型,它似乎也能工作,我不明白如何:) ...
  • 您不必导入任何模型,只需在已安装的应用程序中添加该应用程序即可。
  • 如何从视图中调用该方法?
【解决方案3】:

我发现在 Django 1.5 中有一种快速的方法。检查这个: custom User models

我也注意到了,

User.__unicode__ = User.get_full_name()

Francis Yaconiello 提到的哪些内容不适用于我(Django 1.3)。会引发这样的错误:

TypeError: unbound method get_full_name() must be called with User instance as first argument (got nothing instead)

【讨论】:

    【解决方案4】:

    像这样将get_full_name 猛击到__unicode__ 方法

    User.__unicode__ = User.get_full_name
    

    确保用可调用对象覆盖它,而不是函数的结果。 User.get_full_name() 将因左括号和右括号而失败。

    放在任何包含的文件上,你应该很好。

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 2015-04-27
      • 1970-01-01
      • 2011-09-15
      • 2020-05-07
      • 2011-04-02
      • 2019-08-23
      • 2014-04-07
      • 2010-09-28
      相关资源
      最近更新 更多