Django用户认证系统如何实现自定义
自定义用户认证系统
Django自带的用户认证系统已经可以满足大部分的情况,但是有时候我们需要某些特定的需求。Django支持使用其他认证系统、也可以扩展Django的User模块,完全自定义新的认证模块。
参考:https://docs.djangoproject.com/en/2.0/topics/auth/customizing/
a、拷贝以下代码到model文件中:
fromdjango.dbimportmodels fromdjango.contrib.auth.modelsimport( BaseUserManager,AbstractBaseUser ) classMyUserManager(BaseUserManager): defcreate_user(self,email,name,password=None): """ CreatesandsavesaUserwiththegivenemail,dateof birthandpassword. """ ifnotemail: raiseValueError('Usersmusthaveanemailaddress') user=self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) returnuser defcreate_superuser(self,email,name,password): """ Createsandsavesasuperuserwiththegivenemail,dateof birthandpassword. """ user=self.create_user( email, password=password, name=name, ) user.is_admin=True user.save(using=self._db) returnuser classUserProfile(AbstractBaseUser): '''账号表''' email=models.EmailField( verbose_name='emailaddress', max_length=255, unique=True, ) name=models.CharField(max_length=32) is_active=models.BooleanField(default=True) is_admin=models.BooleanField(default=False) objects=MyUserManager() USERNAME_FIELD='email' REQUIRED_FIELDS=['name'] def__str__(self): returnself.email defhas_perm(self,perm,obj=None): "Doestheuserhaveaspecificpermission?" #Simplestpossibleanswer:Yes,always returnTrue defhas_module_perms(self,app_label): "Doestheuserhavepermissionstoviewtheapp`app_label`?" #Simplestpossibleanswer:Yes,always returnTrue @property defis_staff(self): "Istheuseramemberofstaff?" #Simplestpossibleanswer:Alladminsarestaff returnself.is_admin
注意:email,name等字段都是可以自定义的
b、在admin.py中添加如下代码:
fromdjangoimportforms fromdjango.contribimportadmin fromdjango.contrib.auth.modelsimportGroup fromdjango.contrib.auth.adminimportUserAdminasBaseUserAdmin fromdjango.contrib.auth.formsimportReadOnlyPasswordHashField fromcustomauth.modelsimportMyUser classUserCreationForm(forms.ModelForm): """Aformforcreatingnewusers.Includesalltherequired fields,plusarepeatedpassword.""" password1=forms.CharField(label='Password',widget=forms.PasswordInput) password2=forms.CharField(label='Passwordconfirmation',widget=forms.PasswordInput) classMeta: model=MyUser fields=('email','date_of_birth') defclean_password2(self): #Checkthatthetwopasswordentriesmatch password1=self.cleaned_data.get("password1") password2=self.cleaned_data.get("password2") ifpassword1andpassword2andpassword1!=password2: raiseforms.ValidationError("Passwordsdon'tmatch") returnpassword2 defsave(self,commit=True): #Savetheprovidedpasswordinhashedformat user=super().save(commit=False) user.set_password(self.cleaned_data["password1"]) ifcommit: user.save() returnuser classUserChangeForm(forms.ModelForm): """Aformforupdatingusers.Includesallthefieldson theuser,butreplacesthepasswordfieldwithadmin's passwordhashdisplayfield. """ password=ReadOnlyPasswordHashField() classMeta: model=MyUser fields=('email','password','date_of_birth','is_active','is_admin') defclean_password(self): #Regardlessofwhattheuserprovides,returntheinitialvalue. #Thisisdonehere,ratherthanonthefield,becausethe #fielddoesnothaveaccesstotheinitialvalue returnself.initial["password"] classUserAdmin(BaseUserAdmin): #Theformstoaddandchangeuserinstances form=UserChangeForm add_form=UserCreationForm #ThefieldstobeusedindisplayingtheUsermodel. #TheseoverridethedefinitionsonthebaseUserAdmin #thatreferencespecificfieldsonauth.User. list_display=('email','date_of_birth','is_admin') list_filter=('is_admin',) fieldsets=( (None,{'fields':('email','password')}), ('Personalinfo',{'fields':('date_of_birth',)}), ('Permissions',{'fields':('is_admin',)}), ) #add_fieldsetsisnotastandardModelAdminattribute.UserAdmin #overridesget_fieldsetstousethisattributewhencreatingauser. add_fieldsets=( (None,{ 'classes':('wide',), 'fields':('email','date_of_birth','password1','password2')} ), ) search_fields=('email',) ordering=('email',) filter_horizontal=() #NowregisterthenewUserAdmin... admin.site.register(MyUser,UserAdmin) #...and,sincewe'renotusingDjango'sbuilt-inpermissions, #unregistertheGroupmodelfromadmin. admin.site.unregister(Group)
C、在settings.py中添加配置:
AUTH_USER_MODEL='customauth.MyUser'#customauth指APPname,MyUser指自定义的用户表model类
(这个时候仍然可以使用django.contrib.authimportauthenticate,login,logout等认证方法,只是保存数据的表不一样)
D、创建超级用户
首先我们要新建一个用户名,用来登陆管理网站,可以使用如下命令:
pythonmanage.pycreatesuperuser
输入想要使用的用户名:
Username(leaveblanktouse'administrator'):user01
输入email:
Emailaddress:(在这里输入你的自己的邮箱帐号)
输入密码,需要输入两次,并且输入密码时不会显示出来:
Password:
Password(again):
当两次密码都相同的时候,就会提示超级帐号创建成功。
Superusercreatedsuccessfully.
E、使用:
用前一步创建的用户,登陆后台管理系统http://0.0.0.0:8081/admin/
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。