Django中如何在FilteredSelectMultiple中显示用户全名

7 投票
6 回答
9612 浏览
提问于 2025-04-17 02:49

我正在尝试使用FilteredSelectMultiple这个工具来显示用户列表。目前它只显示用户名。我试着像下面这样重写label_from_instance,但似乎没有效果。我该怎么做才能显示用户的全名呢?

class UserMultipleChoiceField(FilteredSelectMultiple):
    """
    Custom multiple select Feild with full name
    """                                                                                                                                                                 
    def label_from_instance(self, obj):
              return "%s" % (obj.get_full_name())

class TicketForm(forms.Form):
    cc_to  = forms.ModelMultipleChoiceField(queryset=User.objects.filter(is_active=True).order_by('username'), widget=UserMultipleChoiceField("CC TO", is_stacked=True)

6 个回答

4

(供将来参考)

你应该继承 ModelMultipleChoiceField 类:

class UserMultipleChoiceField(forms.ModelMultipleChoiceField):
    """
    Custom multiple select Feild with full name
    """
    def label_from_instance(self, obj):
          return obj.get_full_name()


class TicketForm(forms.Form):
    cc_to  = UserMultipleChoiceField(
            queryset=User.objects.filter(is_active=True).order_by('username'),
            widget=FilteredSelectMultiple("CC TO", is_stacked=True)
        )

另一种解决方案是继承 User 类,并在你的查询集中使用它 (就像这个问题中提到的: Django 在模型表单中显示 get_full_name() 而不是用户名)

class UserFullName(User):
    class Meta:
        proxy = True
        ordering = ["username"]

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

class TicketForm(forms.Form):
    cc_to  = forms.ModelMultipleChoiceField(
            queryset=UserFullName.objects.filter(is_active=True),
            widget=FilteredSelectMultiple("CC TO", is_stacked=True)
        )
15

最简单的解决办法是在一个叫models.py的文件里,导入django.contrib.auth.models.User,然后加上以下内容:

def user_unicode_patch(self):
    return '%s %s' % (self.first_name, self.last_name)

User.__unicode__ = user_unicode_patch

这样做会替换掉User模型的__unicode__()方法,用你自定义的函数来显示你想要的内容。

3

虽然有点晚了,但我觉得这可能对那些想解决类似问题的人有帮助:http://djangosnippets.org/snippets/1642/

撰写回答