如何以Django模型形式显示用户的get

如何以Django模型形式显示用户的get

本文介绍了如何以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的方式作为对类似问题的回答 。它是 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()而不是用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:28