更改 Django ModelChoiceField 以显示用户的全名而不是用户名 [英] Change Django ModelChoiceField to show users' full names rather than usernames
问题描述
我的 Django 应用程序中有一个表单(不是在管理员中),它允许工作人员从下拉列表中选择一个用户.
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)
问题是下拉菜单按用户名显示用户,而我宁愿它从 user.get_full_name() 显示他们的全名,只有在不可用时才使用用户名.我只需要在此页面上进行此更改,在其他地方(例如 admin),我不在乎它是否使用用户名.
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?
谢谢!
推荐答案
你可以设置一个自定义的 ModelChoiceField
,它会返回你想要的任何标签.
You can setup a custom ModelChoiceField
that will return whatever label you'd like.
在 fields.py 或任何适用的地方放置类似的内容.
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)
更多信息可以在这里找到
这篇关于更改 Django ModelChoiceField 以显示用户的全名而不是用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!