我正在检查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
中创建CustomUserChangeFrom
和forms.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
。
我想念什么吗?
答案 0 :(得分:0)
感谢Michael Herman的回答: https://testdriven.io/blog/django-custom-user-model/
在CustomUserAdmin
的{{1}}中,您必须声明admin.py
:
fieldsets