以django形式显示全名,而不是用户名 [英] Display full names in django form, not username
问题描述
用户名
属性,这是登录ID。 由于用户对象存储全名,如何在表单上显示ChoiceField,显示用户的全名,而不是用户名,但是在表单发布后仍然将其链接回正确的用户对象?
如果您有一个常规ChoiceField,但如果您有一个modelChoiceField,则可以执行以下操作:
class UserModelChoiceField(forms.ModelChoiceField):
为用户扩展ModelChoiceField,以便选择
列为'first_name last_name(username)'而不是
'username'
def label_from_instance(self,obj):
return%s %s)%(obj.get_full_name(),obj.username)
类XYZForm(forms.Form):
...
xyz = UserModelChoiceField (User.obj ects.all())
I have a Django app that has activities and objects that have foreign keys to the User object that is defined in django.contrib.auth.models. In doing this, I get the username
property of the user, which is the login id.
Since the User object stores the full name, how do I make a ChoiceField on an form display the full names of the user, not the username, but still link it back to the correct User object after the form is Posted?
Not absolutely sure the following works if you have a regular ChoiceField but if you have a modelChoiceField you can do the following:
class UserModelChoiceField(forms.ModelChoiceField):
"""
Extend ModelChoiceField for users so that the choices are
listed as 'first_name last_name (username)' instead of just
'username'.
"""
def label_from_instance(self, obj):
return "%s (%s)" % (obj.get_full_name(), obj.username)
class XYZForm(forms.Form):
...
xyz = UserModelChoiceField(User.objects.all())
这篇关于以django形式显示全名,而不是用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!