fromdjango import formsfromdjango.contrib import adminfromdjango.contrib.auth.models import Groupfrom django.contrib.auth.admin import UserAdmin asBaseUserAdminfromdjango.contrib.auth.forms import ReadOnlyPasswordHashFieldfromrepository.models import UserProfileclassUserCreationForm(forms.ModelForm): #创建时显示的表单信息"""A form for creating new users. Includes all the required
fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2= forms.CharField(label='Password confirmation', widget=forms.PasswordInput)classMeta:
model=UserProfile
fields= ('email', 'name')
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 don't match")returnpassword2
def save(self, commit=True):
# Save the provided passwordinhashed format
user= super().save(commit=False)
user.set_password(self.cleaned_data["password1"])ifcommit:
user.save()returnuserclassUserChangeForm(forms.ModelForm): #修改时显示的表单信息"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.""" password = ReadOnlyPasswordHashField() #密码字段显示时是hash加密只读字段classMeta:
model=UserProfile
fields= ('email', 'password', 'name', 'is_active', 'is_superuser')
def clean_password(self):
# Regardless of what the user provides,returnthe initial value.
# Thisisdone here, rather than on the field, because the
# field does not have access to the initial valuereturn self.initial["password"]classUserProfileAdmin(BaseUserAdmin): #用于注册的表类
# The forms to add and change user instances
form=UserChangeForm
add_form=UserCreationForm
# The fields to be usedindisplaying the User model.
# Theseoverride the definitions on the baseUserAdmin
# that reference specific fields on auth.User.
list_display= ('email', 'name', 'is_superuser')
list_filter= ('is_superuser',)
fieldsets=( #用于修改
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('name',)}),
('Permissions', {'fields': ('is_active','is_staff','is_superuser','role','user_permissions','groups',)}),
)
# add_fieldsetsisnot a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to usethisattribute when creating a user.
add_fieldsets=( #用于添加
(None, {'classes': ('wide',),'fields': ('email', 'name', 'password1', 'password2')}
),
)
search_fields= ('email',)
ordering= ('email',)
filter_horizontal= ('role','user_permissions',)
# Now register thenewUserAdmin...
admin.site.register(UserProfile, UserProfileAdmin)
# ... and, since we're not using Django's built-inpermissions,
# unregister the Group modelfromadmin.
admin.site.unregister(Group)