You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
2.4 KiB
61 lines
2.4 KiB
from django import forms
|
|
from django.contrib.auth.admin import UserAdmin
|
|
from django.contrib.auth.forms import UserChangeForm
|
|
from django.contrib.auth.forms import UsernameField
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
# Register your models here.
|
|
from .models import BlogUser
|
|
|
|
# 用户创建表单 - 处理新用户创建时的密码验证和保存逻辑
|
|
class BlogUserCreationForm(forms.ModelForm):
|
|
password1 = forms.CharField(label=_('password'), widget=forms.PasswordInput)# 密码字段 - 用户设置的密码输入
|
|
password2 = forms.CharField(label=_('Enter password again'), widget=forms.PasswordInput)# 确认密码字段 - 再次输入密码用于验证一致性
|
|
|
|
class Meta:
|
|
model = BlogUser
|
|
fields = ('email',)
|
|
|
|
def clean_password2(self):# 密码验证方法 - 检查两次输入的密码是否一致
|
|
# Check that the two password entries match
|
|
password1 = self.cleaned_data.get("password1")
|
|
password2 = self.cleaned_data.get("password2")# 获取两次输入的密码值
|
|
if password1 and password2 and password1 != password2:
|
|
raise forms.ValidationError(_("passwords do not match"))# 密码一致性检查 - 如果两次输入不一致则抛出验证错误
|
|
return password2
|
|
|
|
def save(self, commit=True):# 用户保存方法 - 处理密码哈希化和用户来源记录
|
|
# Save the provided password in hashed format
|
|
user = super().save(commit=False)
|
|
user.set_password(self.cleaned_data["password1"])
|
|
# 提交保存 - 设置用户来源为管理后台并保存到数据库
|
|
if commit:
|
|
user.source = 'adminsite'
|
|
user.save()
|
|
return user
|
|
|
|
# 用户修改表单 - 继承Django默认用户修改表单
|
|
class BlogUserChangeForm(UserChangeForm):
|
|
class Meta:
|
|
model = BlogUser
|
|
fields = '__all__'
|
|
field_classes = {'username': UsernameField}
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
|
|
# 用户管理类 - 自定义用户模型在Django后台的显示和管理方式
|
|
class BlogUserAdmin(UserAdmin):
|
|
form = BlogUserChangeForm
|
|
add_form = BlogUserCreationForm
|
|
list_display = (
|
|
'id',
|
|
'nickname',
|
|
'username',
|
|
'email',
|
|
'last_login',
|
|
'date_joined',
|
|
'source')
|
|
list_display_links = ('id', 'username')
|
|
ordering = ('-id',)
|