Django - 用户名为unicode [英] Django - User full name as unicode

查看:92
本文介绍了Django - 用户名为unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ?

我有一个配置文件模型注册我可以定义 __ unicode __(),我应该链接所有的模型吗?似乎不是一个好主意。

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)

我将不得不选择每个对象的 __ unicodes __ t
如何在用户的全名?

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 ?

推荐答案

尝试这样: / p>

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/topics/auth/#django.contrib.auth.models.User.get_full_name

如果unicode的必要条件功能被替换:

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 

这篇关于Django - 用户名为unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆