Addig表单字段添加到Django管理面板中的自定义用户模型

时间:2019-01-24 08:05:23

标签: python django django-admin django-custom-user

我正在检查django for beginners book,测试第8章有关Custom user model的代码。目标是通过对age模型进行子类化,在auth用户模型中添加字段AbstractUser

首先,我们在CustomUser中创建models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

然后在CustomUserCreationFrom中创建CustomUserChangeFromforms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import CustomUser

class CustomUserCreationFrom(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('age',)

class CustomUserChangeFrom(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = CustomUser
        fields = UserChangeForm.Meta.fields

最后,CustomUserAdmin中的admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationFrom, CustomUserChangeFrom
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationFrom
    form = CustomUserChangeFrom
    model = CustomUser
    list_display = ['username', 'email', 'age', 'is_staff',]

admin.site.register(CustomUser, CustomUserAdmin)

当然还要告诉django我们在settings.py中的自定义身份验证模型:

AUTH_USER_MODEL = 'users.CustomUser'

以超级用户身份登录,并且尝试添加新用户时,创建表单中没有字段age

enter image description here

我想念什么吗?

1 个答案:

答案 0 :(得分:0)

感谢Michael Herman的回答: https://testdriven.io/blog/django-custom-user-model/

CustomUserAdmin的{​​{1}}中,您必须声明admin.py

fieldsets