修改 #51

Merged
phm9gvnzi merged 1 commits from djq_branch into master 3 months ago

@ -1,59 +1,80 @@
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.forms import UsernameField
# 修正:导入 UsernameField
from django.contrib.auth.forms import UserChangeForm, UserCreationForm, UsernameField
from django.contrib.auth.models import Group
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 BlogUserCreationForm(UserCreationForm):
"""
自定义用户创建表单
"""
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
fields = ('username', 'email') # 根据你的模型调整
class BlogUserChangeForm(UserChangeForm):
"""
自定义用户修改表单
"""
class Meta:
model = BlogUser
fields = '__all__'
# 现在 UsernameField 已经被正确导入
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class BlogUserAdmin(UserAdmin):
"""
自定义用户Admin界面
"""
form = BlogUserChangeForm
add_form = BlogUserCreationForm
list_display = (
'id',
'nickname',
'nickname', # 确保模型中有此字段
'username',
'email',
'last_login',
'date_joined',
'source')
'source' # 确保模型中有此字段
)
list_display_links = ('id', 'username')
ordering = ('-id',)
# 定义修改用户时显示的字段组
fieldsets = (
(None, {'fields': ('username', 'password')}),
# 确保模型中有 first_name, last_name, nickname 字段,否则移除
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'nickname')}),
(_('Permissions'), {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
}),
# 确保模型中有 source 字段,否则移除
(_('Important dates'), {'fields': ('last_login', 'date_joined', 'source')}),
)
# 定义创建用户时显示的字段组
add_fieldsets = (
(None, {
'classes': ('wide',),
# 确保模型中有 nickname 字段,否则移除
'fields': ('username', 'email', 'nickname', 'password1', 'password2'),
}),
)
# 注册自定义用户模型和Admin类
admin.site.register(BlogUser, BlogUserAdmin)
# 如果你不想在Admin中管理Groups可以取消下面这行的注释
# admin.site.unregister(Group)
Loading…
Cancel
Save