django:顺序和显示名称冲突
我有一个使用用户作为 forgignKey 的模型。在管理员中,我需要它显示为全名而不是用户名。然后我应用
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
它作为带有全名的下拉列表运行良好。然后我想按字母顺序对它们进行排序。 然后我就
class CollaboratorForm(forms.ModelForm):
collaborator = forms.ModelChoiceField(queryset=User.objects.order_by('first_name'))
#assert False,collaborator
class Meta:
model = Collaborator
按照这个申请了。全名再次变成用户名。如果我删除它,它就会变成全名。 那么我怎样才能保留这两个功能呢?
谢谢
i have a model using user as a forgignKey. and in the admin, i need it show as full name instread of username. then i applied
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
it works fine as a dropdown list with fullnames. then i want to sort them in alphabetical order.
then i appplied
class CollaboratorForm(forms.ModelForm):
collaborator = forms.ModelChoiceField(queryset=User.objects.order_by('first_name'))
#assert False,collaborator
class Meta:
model = Collaborator
as this applied. the full names becomes username again. if i remove it, it becomes full names.
so how can i keep both features?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试子类化
ModelChoiceField
并重写label_for_instance
方法以显示全名。然后在模型表单中使用新字段。
Try subclassing
ModelChoiceField
and override thelabel_for_instance
method to display the full name.Then use the new field in your model form.