如何在 Django 模型表单中显示用户的 get_full_name() 而不是用户名? [英] How to display a user's get_full_name() instead of the username in a Django model form?

查看:16
本文介绍了如何在 Django 模型表单中显示用户的 get_full_name() 而不是用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个引用 ForeignKey(User) 字段的模型.

I have a model that references a ForeignKey(User) field.

当用户在他的表单上选择一个项目时,我希望他们能够看到 get_full_name() 而不仅仅是 username.

When a user selects an item on his form I would like them to be able to see the get_full_name() instead of just the username.

class Books(models.Model):
     author = models.ForeignKey(User)

推荐答案

这可以通过多种方式完成.

This can be done several ways.

创建一个 User 的代理子类并覆盖它的 __unicode__() 方法以返回用户的全名.

Create a proxy subclass of User and override its __unicode__() method to return user's full name.

class UserFullName(User):
    class Meta:
        proxy = True

    def __unicode__(self):
        return self.get_full_name()

现在在您的模型表单中,使用 UserFullName 来检索用户.

Now in your model form, use UserFullName to retrieve users.

class BookForm(forms.ModelForm):
    author = forms.ModelChoiceField(queryset=UserFullName.objects.all())
    class Meta:
        model = Book

<小时>

另一种方法是在表单的构造函数中动态填充选项.


Another way is to dynamically populate choices in form's constructor.

class BookForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)
        users = User.objects.all()
        self.fields['author'].choices = [(user.pk, user.get_full_name()) for user in users]

    class Meta:
        model = Book

<小时>

也许,lazerscience 展示了最djangonic"的方式作为对类似问题的回答 Django 表单:如何动态创建 ModelChoiceField 标签.它继承了 ModelChoiceField 并覆盖了其用于提供选择标签的 label_from_instance() 方法.


Perhaps, the most "djangonic" way is demonstrated by lazerscience as an answer to the similar question Django forms: how to dynamically create ModelChoiceField labels. It subclasses ModelChoiceField and overrides its label_from_instance() method that is intended to provide choice labels.

class UserFullnameChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return smart_unicode(obj.get_full_name())

class BookForm(forms.ModelForm):
    author = UserFullnameChoiceField(queryset=User.objects.all())

    class Meta:
        model = Book

这篇关于如何在 Django 模型表单中显示用户的 get_full_name() 而不是用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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