以django形式显示全名,而不是用户名 [英] Display full names in django form, not username

查看:262
本文介绍了以django形式显示全名,而不是用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django应用程序,其活动和对象具有django.contrib.auth.models中定义的User对象的外键。这样做,我得到用户的用户名属性,这是登录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屋!

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