更改Django ModelChoiceField以显示用户的全名而不是用户名 [英] Change Django ModelChoiceField to show users' full names rather than usernames

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

问题描述

我的Django应用程式(不在管理员)中有一个表单,允许员工从下拉列表中选择一个用户。

  forms.ModelChoiceField(queryset = User.objects.filter(is_staff = False),required = False)

问题是下拉列表以用户名显示用户,而我宁愿从user.get_full_name()显示其全名,只有在不可用时才使用用户名。我只需要在这个页面上进行这个更改,在管理员等其他地方,我不在乎它是否使用用户名。



有没有办法我可以做到这一点?



谢谢!

解决方案

您可以设置自定义 ModelChoiceField ,将返回您想要的任何标签。



将这样的内容放在fields.py或适用的位置。

$ b

  class UserModelChoiceField(ModelChoiceField):
def label_from_instance(self,obj):
return obj.get_full_name )

然后创建表单时,只需使用该字段

  UserModelChoiceField(queryset = User.objects.filter(is_staff = False),required = False)

可以在这里找到更多信息


I have a form in my Django app (not in admin) that allows staff members to select a user from a dropdown.

forms.ModelChoiceField(queryset = User.objects.filter(is_staff=False), required = False)

The problem is that the dropdown shows users by usernames whereas I'd rather it show their full name from user.get_full_name() and use username only if that is not available. I only really need this change on this page, in other places like admin, I don't care if it uses username.

Is there a way I can do this?

Thanks!

解决方案

You can setup a custom ModelChoiceField that will return whatever label you'd like.

Place something like this within a fields.py or wherever applicable.

class UserModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
         return obj.get_full_name()

Then when creating your form, simply use that field

 UserModelChoiceField(queryset=User.objects.filter(is_staff=False), required = False)

More info can be found here

这篇关于更改Django ModelChoiceField以显示用户的全名而不是用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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