django:命令和显示名称冲突

时间:2010-08-17 21:40:48

标签: django django-admin

我有一个使用user作为forgignKey的模型。在管理员,我需要它显示为用户名的全名instread。然后我申请了

class CollaboratorInLine(admin.StackedInline):
    model = Collaborator
    #list_display = ('collaborator__collaborator_first_name')
    extra = 0
    form =CollaboratorForm
    #raw_id_fields=("collaborator",)

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(CollaboratorInLine, self).formfield_for_foreignkey(
                                                db_field, request, **kwargs)
        if db_field.rel.to == User:
            field.label_from_instance = self.get_user_label
        return field
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        field = super(CollaboratorInLine, self).formfield_for_manytomany(
                                                db_field, request, **kwargs)
        if db_field.rel.to == User:
            field.label_from_instance = self.get_user_label
        return field
    def get_user_label(self, user):   
        name = user.get_full_name()  
        return name

它可以作为带有全名的下拉列表正常工作。然后我想按字母顺序对它们进行排序。 然后我appplied

class CollaboratorForm(forms.ModelForm):
    collaborator = forms.ModelChoiceField(queryset=User.objects.order_by('first_name'))
    #assert False,collaborator
    class Meta:
        model = Collaborator

如此应用。全名再次成为用户名。如果我删除它,它会成为全名。 那我怎么能保留这两个功能呢?

感谢

1 个答案:

答案 0 :(得分:0)

尝试继承ModelChoiceField并覆盖label_for_instance方法以显示全名。

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

然后在模型表单中使用新字段。

class CollaboratorForm(forms.ModelForm):
        collaborator = MyModelChoiceField(queryset=User.objects.order_by('first_name'))
        #assert False,collaborator
        class Meta:
            model = Collaborator