如何使用自定义用户从Django管理中的用户继承字段?

pyt*_*had 4 python django django-admin

我想将我settings.AUTH_USER_MODEL的模型添加到我的管理员中User。我用在文档中找到的代码片段注册它:

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'bdate')
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('bdate', 'website', 'location')}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()
Run Code Online (Sandbox Code Playgroud)

在字段集中,Personal info我添加了所有自定义信息。现在我还想显示所有继承的字段,如first_nameusername等。我可以将它们一一添加到字段集中,但我不确定这是否是正确的方法。

有没有一种方法可以从User模型继承它们而无需明确指定?

Ale*_*zov 5

您可以利用ModelAdmin.get_fieldsets()

class UserAdmin(BaseUserAdmin):
    def get_fieldsets(self, request, obj=None):
        fieldsets = list(super(UserAdmin, self).get_fieldsets(request, obj))
        # update the `fieldsets` with your specific fields
        fieldsets.append(
            ('Personal info', {'fields': ('bdate', 'website', 'location')}))
        return fieldsets
Run Code Online (Sandbox Code Playgroud)