我有一个自定义用户模型,它通过AbstractUser
添加的自定义字段进行子类化。
# model.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
ADM = 'admin'
MEMBER = 'member'
ROLE_CH = ((ADM, 'Administrator'), (MEMBER, 'Member'))
role = models.CharField(max_length=20, choices=ROLE_CH, blank=True)
该模型也注册为默认的身份验证模型settings.py
# settings.py
AUTH_USER_MODEL = "main.CustomUser"
然后admin.py
根据文档,我创建了一个扩展的自定义表单,UserCreationForm
然后将其注册给自定义用户。
# admin.py
from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('role',)
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
admin.site.register(CustomUser, CustomUserAdmin)
但是,它没有按预期工作。表单仍然是默认的,Add User
即 only username
,password
并且password confirmation
存在字段。该role
字段不出现。