如何更改 django admin 外键下拉列表中的显示文本

发布于 2024-09-06 08:25:28 字数 202 浏览 6 评论 0原文

我有一个任务列表,能够分配用户。所以我在数据库中有用户模型的外键。但是,下拉菜单中默认显示的是用户名,我想显示全名(名字和姓氏)而不是用户名。如果外键指向我自己的类之一,我可以只更改模型中的 str 函数,但是 User 是一个 django 身份验证模型,所以我不能轻易地直接更改它,对吧?

有人知道如何做到这一点吗?

多谢!

I have a task list, with ability to assign users. So I have foreignkey to User model in the database. However, the default display is username in the dropdown menu, I would like to display full name (first last) instead of the username. If the foreignkey is pointing to one of my own classes, I can just change the str function in the model, but User is a django authentication model, so I can't easily change it directly right?

Anyone have any idea how to accomplish this?

Thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

混浊又暗下来 2024-09-13 08:25:28

您可以为您的任务模型创建一个新的 ModelForm,它将显示您喜欢的用户列表(此处的代码假定名为 Task 的模型具有“user”属性):

def get_user_full_name_choices:
    return [(user, user.get_full_name()) for user in User.objects.all()]

class TaskAdminForm(forms.ModelForm):
    class Meta:
        model = Task
    user = forms.ChoiceField(choices=get_user_full_name_choices)

然后,告诉您的 ModelAdmin 类使用新表单:

class TaskAdmin(admin.ModelAdmin):
    form = TaskAdminForm

You can create a new ModelForm for your Task model, which will display the list of users however you like (code here assumes a model named Task with a 'user' attribute):

def get_user_full_name_choices:
    return [(user, user.get_full_name()) for user in User.objects.all()]

class TaskAdminForm(forms.ModelForm):
    class Meta:
        model = Task
    user = forms.ChoiceField(choices=get_user_full_name_choices)

Then, tell your ModelAdmin class to use the new form:

class TaskAdmin(admin.ModelAdmin):
    form = TaskAdminForm
一紙繁鸢 2024-09-13 08:25:28

还有另一种选择:

USERS = [(user.id, user.get_full_name()) for user in User.objects.all()]
USERS.insert(0, ('', '----'))

class TaskAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    super(TaskAdminForm, self).__init__(*args, **kwargs)
    self.fields['user'].choices=USERS

There is another choice:

USERS = [(user.id, user.get_full_name()) for user in User.objects.all()]
USERS.insert(0, ('', '----'))

class TaskAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    super(TaskAdminForm, self).__init__(*args, **kwargs)
    self.fields['user'].choices=USERS
浪漫之都 2024-09-13 08:25:28

更通用、更详细的解决方案,使用 ModelChoiceField 作为基础。避免摆弄查询集,只专注于修改下拉列表中的可见值。

  1. 创建您自己的表单字段:
class CustomLabelChoiceField(forms.ModelChoiceField):
     def label_from_instance(self, obj):
         return "Howdy {}".format(obj.name)
  1. 将其与 formfield_for_dbfield (如链接中所示)一起使用,或者更详细地在您的管理表单中使用:
class TaskAdminForm(forms.ModelForm):
    user = CustomLabelChoiceField(queryset=User.objects.all()
    class Meta:
        model = Task


# obviously, link it with your admin
class TaskAdmin(admin.ModelAdmin):
    form = TaskAdminForm

A more generic, verbose solution, using a ModelChoiceField as base. Avoids fiddling with querysets, just focusing on modifying the visible value in the dropdown.

  1. create your own formfield:
class CustomLabelChoiceField(forms.ModelChoiceField):
     def label_from_instance(self, obj):
         return "Howdy {}".format(obj.name)
  1. use it either with formfield_for_dbfield (as in the link), or, more verbose, in your admin form:
class TaskAdminForm(forms.ModelForm):
    user = CustomLabelChoiceField(queryset=User.objects.all()
    class Meta:
        model = Task


# obviously, link it with your admin
class TaskAdmin(admin.ModelAdmin):
    form = TaskAdminForm
浊酒尽余欢 2024-09-13 08:25:28

通过重写 formfield_for_foreignkey( ),您可以向Django Admin显示“first_name”和“last_name”的组合,而无需创建自定义“表单。 ModelChoiceField”自定义“forms.ModelForm”如下所示:

@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == "user":
            formfield.label_from_instance = lambda obj: f'{obj.first_name} ({obj.last_name})'
        return formfield

By overriding formfield_for_foreignkey(), you can display the combination of "first_name" and "last_name" to Django Admin without creating a custom "forms.ModelChoiceField" and a custom "forms.ModelForm" as shown below:

@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == "user":
            formfield.label_from_instance = lambda obj: f'{obj.first_name} ({obj.last_name})'
        return formfield
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文