扩展AbstractUser时如何将emailfield设置为必填?
我想知道如何重写AbstractUser的emailfield模型以根据需要进行设置。目前,我的表单列出了电子邮件字段,但未按要求设置。默认情况下,不是所有型号都需要吗?
从文档中可以看到在创建超级用户时如何将字段设置为必填字段的示例,但是我不确定如何在不使用AbstractBaseUser的情况下通过AbstractUser模型完成任务。
model.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
display_name = models.CharField(max_length=50, unique=True)
bio = models.CharField(max_length=500, blank=True, null=True)
authorization_code = models.CharField(max_length=20)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta (UserCreationForm):
model = CustomUser
fields = ('username', 'email', 'display_name', 'authorization_code')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'bio')
admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username', 'display_name', 'bio']
list_display_links = ('username', 'display_name')
fieldsets = (
(None, {'fields': ('username', 'display_name', 'email', 'bio', 'password')}),
('Permissions', {'fields': ('is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'display_name', 'email', 'bio', 'password1', 'password2', 'is_staff', 'is_active')}
),
)
admin.site.register(CustomUser, CustomUserAdmin)
解决方案:
# It was as simple as updating my CustomUser model as shown:
class CustomUser(AbstractUser):
display_name = models.CharField(max_length=50, unique=True)
bio = models.CharField(max_length=500, blank=True, null=True)
authorization_code = models.CharField(max_length=20)
email = models.EmailField(max_length=50, unique=True)
答案 0 :(得分:0)
您可以通过覆盖 AbstractBaseUser 中的email
。
from django.contrib.auth.models import AbstractBaseUser, UserManager
class User(AbstractBaseUser):
email = models.EmailField(_('email address'), blank=False)
objects = UserManager()