Django 部署一个简单的用户后台
第一步编写models.py,下面是通过在myauth.py 文件models.py 的用户内容,再在models.py中引入这个文件
models.py内容如下:
from__future__importunicode_literalsfromdjango.dbimportmodelsimportmyauth#Createyourmodelshere.
myauth.py内容
#!/usr/bin/python#-*-coding:utf-8-*-__author__='gaogd'fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimport(BaseUserManager,AbstractBaseUser)classMyUserManager(BaseUserManager):defcreate_user(self,email,name,date_of_birth,password=None):"""CreatesandsavesaUserwiththegivenemail,dateofbirthandpassword."""ifnotemail:raiseValueError('Usersmusthaveanemailaddress')user=self.model(email=self.normalize_email(email),date_of_birth=date_of_birth,name=name##用户名)user.set_password(password)user.save(using=self._db)returnuserdefcreate_superuser(self,email,name,date_of_birth,password):"""Createsandsavesasuperuserwiththegivenemail,dateofbirthandpassword."""user=self.create_user(email,password=password,name=name,date_of_birth=date_of_birth,)user.is_admin=Trueuser.save(using=self._db)returnuserclassMyUser(AbstractBaseUser):email=models.EmailField(verbose_name='emailaddress',max_length=255,unique=True,)name=models.CharField(u'名字',max_length=32)token=models.CharField(u'token',max_length=128,default=None,blank=True,null=True)department=models.CharField(u'部门',max_length=32,default=None,blank=True,null=True)mobile=models.CharField(u'手机',max_length=32,default=None,blank=True,null=True)memo=models.TextField(u'备注',blank=True,null=True,default=None)date_of_birth=models.DateField()is_active=models.BooleanField(default=True)is_admin=models.BooleanField(default=False)objects=MyUserManager()USERNAME_FIELD='email'REQUIRED_FIELDS=['name']defget_full_name(self):#Theuserisidentifiedbytheiremailaddressreturnself.emaildefget_short_name(self):#Theuserisidentifiedbytheiremailaddressreturnself.emaildef__unicode__(self):#__unicode__onPython2returnself.emaildefhas_perm(self,perm,obj=None):"Doestheuserhaveaspecificpermission?"#Simplestpossibleanswer:Yes,alwaysreturnTruedefhas_module_perms(self,app_label):"Doestheuserhavepermissionstoviewtheapp`app_label`?"#Simplestpossibleanswer:Yes,alwaysreturnTrue@propertydefis_staff(self):"Istheuseramemberofstaff?"#Simplestpossibleanswer:Alladminsarestaffreturnself.is_admin
2.编写admin.py内容,同样相关用户认证的admin.py内容,我通过编写到其他文件(auth_admin.py)文件中,再在admin.py中引入这个文件
admin.py内容:
fromdjango.contribimportadminimportauth_admin#Registeryourmodelshere.
auth_admin.py内容:
#!/usr/bin/python#-*-coding:utf-8-*-__author__='gaogd'fromdjangoimportformsfromdjango.contribimportadminfromdjango.contrib.auth.modelsimportGroupfromdjango.contrib.auth.adminimportUserAdminfromdjango.contrib.auth.formsimportReadOnlyPasswordHashFieldfrommyauthimportMyUserclassUserCreationForm(forms.ModelForm):"""Aformforcreatingnewusers.Includesalltherequiredfields,plusarepeatedpassword."""password1=forms.CharField(label='Password',widget=forms.PasswordInput)password2=forms.CharField(label='Passwordconfirmation',widget=forms.PasswordInput)classMeta:model=MyUserfields=('email','date_of_birth')defclean_password2(self):#Checkthatthetwopasswordentriesmatchpassword1=self.cleaned_data.get("password1")password2=self.cleaned_data.get("password2")ifpassword1andpassword2andpassword1!=password2:raiseforms.ValidationError("Passwordsdon'tmatch")returnpassword2defsave(self,commit=True):#Savetheprovidedpasswordinhashedformatuser=super(UserCreationForm,self).save(commit=False)user.set_password(self.cleaned_data["password1"])ifcommit:user.save()returnuserclassUserChangeForm(forms.ModelForm):"""Aformforupdatingusers.Includesallthefieldsontheuser,butreplacesthepasswordfieldwithadmin'spasswordhashdisplayfield."""password=ReadOnlyPasswordHashField()classMeta:model=MyUserfields=('email','password','date_of_birth','is_active','is_admin')defclean_password(self):#Regardlessofwhattheuserprovides,returntheinitialvalue.#Thisisdonehere,ratherthanonthefield,becausethe#fielddoesnothaveaccesstotheinitialvaluereturnself.initial["password"]classMyUserAdmin(UserAdmin):#Theformstoaddandchangeuserinstancesform=UserChangeFormadd_form=UserCreationForm#ThefieldstobeusedindisplayingtheUsermodel.#TheseoverridethedefinitionsonthebaseUserAdmin#thatreferencespecificfieldsonauth.User.list_display=('email','name','date_of_birth','is_admin')list_filter=('is_admin',)fieldsets=((None,{'fields':('email','name','password')}),('Personalinfo',{'fields':('department','mobile','memo','token','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,MyUserAdmin)#...and,sincewe'renotusingDjango'sbuilt-inpermissions,#unregistertheGroupmodelfromadmin.admin.site.unregister(Group)#Createyourmodelshere.
3.在settings.py文件中加上下面一会代码
AUTH_USER_MODEL=
#上面的BaseLvnian是我的app名称。MyUser是我myauth.py文件中定义用户的类,类名称是MyUser
4。最后执行下面命令即可pythonmanage.pymakemigrationspythonmanage.pymigrate故障解决:出现下面错误ValueError:Dependencyonappwithnomigrations:BaseLvnian原因:还没有生成相关的用户表,所有在settings中应用下面变量就会出现上面的错误AUTH_USER_MODEL='BaseLvnian.MyUser'解决执行下面命令生成相关用户表即可:pythonmanage.pymakemigrationspythonmanage.pymigrate
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。