尽管覆盖了默认管理,但自定义 AbstractUser 的新字段未显示在 Django 管理中

New field of custom AbstractUser not showing up in Django admin despite overriding the default admin

我已将字段 introduction 添加到我的 CustomUser 模型并进行了适当的迁移:

class CustomUser(AbstractUser):

    introduction = models.CharField(max_length=5000, null=True, blank=True, default="")

    def get_absolute_url(self):
        return reverse('user_detail', args=[str(self.username)])

admin.py 覆盖用户的默认管理员:

CustomUser = get_user_model()

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['username', 'introduction',]

admin.site.register(CustomUser,CustomUserAdmin)

forms.py:

class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = get_user_model()
        fields = ('username',)

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = get_user_model()
        fields = ('username', 'introduction',)

尽管如此,当我尝试在 Django 管理中修改用户时,introduction 字段没有出现。

我正在使用 Django 3.0.1。

您需要在 CustomUserAdmin 的 fieldsets 列表中添加 introduction 字段名称,因为它已经在基础 class 中实现这就是不在 django admin 中自动显示新字段的原因。

根据 django 文档:

fieldsets is a list of two-tuples, in which each two-tuple represents a on the admin form page. (A is a “section” of the form.)

The two-tuples are in the format (name, field_options), where name is a string representing the title of the fieldset and field_options is a dictionary of information about the fieldset, including a list of fields to be displayed in it.

我从 AbstractUser class 获得了 fieldsets 并通过 introduction 字段进行了扩展。此代码段必须帮助您在管理员中显示新的用户模型字段:

from django.utils.translation import gettext, gettext_lazy as _

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['username', 'introduction',]
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'introduction')}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

我不知道这是否是理想的方法,但我所做的是对 UserAdmin 的 field_sets 进行如下更改:

class CustomUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password','introduction')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser

我刚刚添加了对字段的介绍,它出现在管理站点上