Django 自定义模型,当管理员创建用户时电子邮件字段禁用填充
Django Custom Model, Email Field disable for filling when Create User by Admin
- 我将默认用户模型更改为我的自定义用户模型并使用电子邮件登录。
- 登录管理员并尝试创建新用户后,电子邮件字段无法填写。喜欢下面的截图。
- 我在解决一些其他问题时删除了
db.sqlite3
。但稍后已经重建。
python manage.py createsuperuser
仍然有效。我可以通过终端创建一个超级用户。
代码在这里
./accounts/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# Register your models here.
from .models import Account
class AccountAdmin(UserAdmin):
list_display = ('email', 'date_joined', 'last_login', 'is_admin')
search_fields = ('email',)
readonly_fields = ('email', 'date_joined', 'last_login')
ordering = ('email',) # solution for E033
filter_horizontal = ()
list_filter = ()
fieldsets = (
(None, {'fields': ('email', 'password')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
admin.site.register(Account, AccountAdmin)
./accounts/backends.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailAuthBackend(ModelBackend):
def authenticate(self, request, email=None, password=None, **kwargs):
UserModel = get_user_model()
if email is None:
email = kwargs.get(UserModel.USERNAME_FIELD)
if email is None or password is None:
return
try:
user = UserModel._default_manager.get_by_natural_key(email)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
./accounts/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class AccountManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("User must register with email.")
user = self.model(
email = self.normalize_email(email),
)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email = self.normalize_email(email),
password = password,
)
user.is_staff = True
user.is_admin = True
user.is_superuser = True
user.save(using=self.db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_activate = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
objects = AccountManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
./accounts/views.py
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate
from .forms import RegisterationForm, LogInForm
class HomePageView(TemplateView):
template_name = 'index.html'
def RegisterView(request):
user = request.user
if user.is_authenticated:
return redirect('home')
context = {}
if request.POST:
form = RegisterationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user, backend='accounts.backends.EmailAuthBackend')
return redirect('home')
else:
form = RegisterationForm()
context['register_form'] = form
return render(request, 'accounts/register.html', context)
def LogInView(request):
user = request.user
if user.is_authenticated:
return redirect('home')
context = {}
if request.POST:
form = LogInForm(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
login(request, user, backend='accounts.backends.EmailAuthBackend')
return redirect('home')
else:
form = LogInForm()
context['login_form'] = form
return render(request, "accounts/login.html", context)
def LogOutView(request):
logout(request)
return redirect('home')
./accounts/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate
from .models import Account
class RegisterationForm(UserCreationForm):
email = forms.EmailField(label='email', error_messages={
'invalid': 'Email Invaild',
'required':'Enter email please.'
})
password1 = forms.EmailField(error_messages={'required':'Enter password please.'})
password2 = forms.EmailField(error_messages={'required':'Enter password confirmation please.'})
error_messages = {
'password_mismatch': ('Two passwords did not match.'),
}
class Meta:
model = Account
fields = ('email', 'password1', 'password2')
def clean_email(self):
email = self.cleaned_data['email']
try:
account = Account.objects.get(email=email)
except Exception as e:
return email
raise forms.ValidationError(f'{email} has been registered.')
class LogInForm(forms.ModelForm):
email = forms.EmailField(error_messages={'required':'Enter email.'})
password = forms.CharField(error_messages={'required':'Enter password.'})
class Meta:
model = Account
fields = ('email', 'password')
def clean(self):
if self.is_valid():
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError("Login Fail!")
我也使用自定义密码验证器。
./accounts/validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
class CustomizePasswordValidator():
def __init__(self, min_length=8):
self.min_length = min_length
def validate(self, password, user=None):
special_characters = "[~\!@#$%\^&\*\(\)_\+{}\":;'\[\]]"
if ( len(password) < 8 ) \
or ( password.isalpha() ) \
or ( password.isnumeric() ) \
or ( password in special_characters) :
raise ValidationError(_('Please enter more than 8 nums and alphabet combination.'))
def get_help_text(self):
return ""
./confif/settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ os.path.join(BASE_DIR, 'templates').replace('\', '/') ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
#{
# 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
#},
#{
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
#},
#{
# 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
#},
#{
# 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
#},
{
'NAME': 'accounts.validators.CustomizePasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
AUTH_USER_MODEL = 'accounts.Account'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.AllowAllUsersModelBackend',
'accounts.backends.EmailAuthBackend',
)
有没有人遇到过类似的情况?
您的管理员 class AccountAdmin
继承自 UserAdmin
。如果您检查它的实现,它会设置 add_form = UserCreationForm
,它在 Meta
class 中有以下 line [Github code]:fields = ("username",)
.
因为您已经创建了一个继承自 UserCreationForm
的自定义表单,您应该在您的管理员中进行设置 class:
from .forms import RegisterationForm
class AccountAdmin(UserAdmin):
...
# Remove ↓
readonly_fields = (<s>'email',</s> 'date_joined', 'last_login')
...
add_form = RegisterationForm
- 我将默认用户模型更改为我的自定义用户模型并使用电子邮件登录。
- 登录管理员并尝试创建新用户后,电子邮件字段无法填写。喜欢下面的截图。
- 我在解决一些其他问题时删除了
db.sqlite3
。但稍后已经重建。 python manage.py createsuperuser
仍然有效。我可以通过终端创建一个超级用户。
代码在这里
./accounts/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# Register your models here.
from .models import Account
class AccountAdmin(UserAdmin):
list_display = ('email', 'date_joined', 'last_login', 'is_admin')
search_fields = ('email',)
readonly_fields = ('email', 'date_joined', 'last_login')
ordering = ('email',) # solution for E033
filter_horizontal = ()
list_filter = ()
fieldsets = (
(None, {'fields': ('email', 'password')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
admin.site.register(Account, AccountAdmin)
./accounts/backends.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailAuthBackend(ModelBackend):
def authenticate(self, request, email=None, password=None, **kwargs):
UserModel = get_user_model()
if email is None:
email = kwargs.get(UserModel.USERNAME_FIELD)
if email is None or password is None:
return
try:
user = UserModel._default_manager.get_by_natural_key(email)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
./accounts/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class AccountManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("User must register with email.")
user = self.model(
email = self.normalize_email(email),
)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email = self.normalize_email(email),
password = password,
)
user.is_staff = True
user.is_admin = True
user.is_superuser = True
user.save(using=self.db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_activate = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
objects = AccountManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
./accounts/views.py
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate
from .forms import RegisterationForm, LogInForm
class HomePageView(TemplateView):
template_name = 'index.html'
def RegisterView(request):
user = request.user
if user.is_authenticated:
return redirect('home')
context = {}
if request.POST:
form = RegisterationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user, backend='accounts.backends.EmailAuthBackend')
return redirect('home')
else:
form = RegisterationForm()
context['register_form'] = form
return render(request, 'accounts/register.html', context)
def LogInView(request):
user = request.user
if user.is_authenticated:
return redirect('home')
context = {}
if request.POST:
form = LogInForm(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
login(request, user, backend='accounts.backends.EmailAuthBackend')
return redirect('home')
else:
form = LogInForm()
context['login_form'] = form
return render(request, "accounts/login.html", context)
def LogOutView(request):
logout(request)
return redirect('home')
./accounts/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate
from .models import Account
class RegisterationForm(UserCreationForm):
email = forms.EmailField(label='email', error_messages={
'invalid': 'Email Invaild',
'required':'Enter email please.'
})
password1 = forms.EmailField(error_messages={'required':'Enter password please.'})
password2 = forms.EmailField(error_messages={'required':'Enter password confirmation please.'})
error_messages = {
'password_mismatch': ('Two passwords did not match.'),
}
class Meta:
model = Account
fields = ('email', 'password1', 'password2')
def clean_email(self):
email = self.cleaned_data['email']
try:
account = Account.objects.get(email=email)
except Exception as e:
return email
raise forms.ValidationError(f'{email} has been registered.')
class LogInForm(forms.ModelForm):
email = forms.EmailField(error_messages={'required':'Enter email.'})
password = forms.CharField(error_messages={'required':'Enter password.'})
class Meta:
model = Account
fields = ('email', 'password')
def clean(self):
if self.is_valid():
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError("Login Fail!")
我也使用自定义密码验证器。
./accounts/validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
class CustomizePasswordValidator():
def __init__(self, min_length=8):
self.min_length = min_length
def validate(self, password, user=None):
special_characters = "[~\!@#$%\^&\*\(\)_\+{}\":;'\[\]]"
if ( len(password) < 8 ) \
or ( password.isalpha() ) \
or ( password.isnumeric() ) \
or ( password in special_characters) :
raise ValidationError(_('Please enter more than 8 nums and alphabet combination.'))
def get_help_text(self):
return ""
./confif/settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ os.path.join(BASE_DIR, 'templates').replace('\', '/') ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
#{
# 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
#},
#{
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
#},
#{
# 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
#},
#{
# 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
#},
{
'NAME': 'accounts.validators.CustomizePasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
AUTH_USER_MODEL = 'accounts.Account'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.AllowAllUsersModelBackend',
'accounts.backends.EmailAuthBackend',
)
有没有人遇到过类似的情况?
您的管理员 class AccountAdmin
继承自 UserAdmin
。如果您检查它的实现,它会设置 add_form = UserCreationForm
,它在 Meta
class 中有以下 line [Github code]:fields = ("username",)
.
因为您已经创建了一个继承自 UserCreationForm
的自定义表单,您应该在您的管理员中进行设置 class:
from .forms import RegisterationForm
class AccountAdmin(UserAdmin):
...
# Remove ↓
readonly_fields = (<s>'email',</s> 'date_joined', 'last_login')
...
add_form = RegisterationForm