参考官网的例子,做了简单修改。

index/models.py

fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimport(BaseUserManager,AbstractBaseUser)classMyUserManager(BaseUserManager):defcreate_user(self,name,email,password=None):"""CreatesandsavesaUserwiththegivenemail,dateofbirthandpassword."""#ifnotname:#raiseValueError('Usersmusthaveanuser')user=self.model(name=name,email=self.normalize_email(email),#date_of_birth=date_of_birth,)user.set_password(password)user.save(using=self._db)returnuserdefcreate_superuser(self,name,email,password):"""Createsandsavesasuperuserwiththegivenemail,dateofbirthandpassword."""user=self.create_user(name,email,password=password,)user.is_admin=Trueuser.save(using=self._db)returnuserclassUserProfile(AbstractBaseUser):name=models.CharField(verbose_name='用户名',max_length=255,unique=True,)email=models.EmailField(verbose_name='邮箱',max_length=255,)#date_of_birth=models.DateField()is_active=models.BooleanField(default=True)is_admin=models.BooleanField(default=False)objects=MyUserManager()USERNAME_FIELD='name'REQUIRED_FIELDS=['email']defget_full_name(self):#Theuserisidentifiedbytheiremailaddressreturnself.namedefget_short_name(self):#Theuserisidentifiedbytheiremailaddressreturnself.namedef__str__(self):#__unicode__onPython2returnself.namedefhas_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_adminclassMeta:db_table="UserProfile"verbose_name="用户"verbose_name_plural=verbose_name




index/admin.py

fromdjango.contribimportadminfromdjangoimportformsfromdjango.contrib.auth.modelsimportGroupfromdjango.contrib.auth.adminimportUserAdminasBaseUserAdminfromdjango.contrib.auth.formsimportReadOnlyPasswordHashFieldfromindex.modelsimportUserProfileclassUserCreationForm(forms.ModelForm):"""Aformforcreatingnewusers.Includesalltherequiredfields,plusarepeatedpassword."""password1=forms.CharField(label='Password',widget=forms.PasswordInput)password2=forms.CharField(label='Passwordconfirmation',widget=forms.PasswordInput)classMeta:model=UserProfilefields=('name','is_active','is_admin')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=UserProfilefields=('name','password','is_active','is_admin')defclean_password(self):#Regardlessofwhattheuserprovides,returntheinitialvalue.#Thisisdonehere,ratherthanonthefield,becausethe#fielddoesnothaveaccesstotheinitialvaluereturnself.initial["password"]classUserAdmin(BaseUserAdmin):#Theformstoaddandchangeuserinstancesform=UserChangeFormadd_form=UserCreationForm#ThefieldstobeusedindisplayingtheUsermodel.#TheseoverridethedefinitionsonthebaseUserAdmin#thatreferencespecificfieldsonauth.User.list_display=('name','email','is_admin')list_filter=('is_admin',)fieldsets=((None,{'fields':('name','password')}),('Personalinfo',{'fields':('email',)}),('Permissions',{'fields':('is_admin',)}),)#add_fieldsetsisnotastandardModelAdminattribute.UserAdmin#overridesget_fieldsetstousethisattributewhencreatingauser.add_fieldsets=((None,{'classes':('wide',),'fields':('name','password1','password2')}),)search_fields=('name',)ordering=('name',)filter_horizontal=()#NowregisterthenewUserAdmin...admin.site.register(UserProfile,UserAdmin)#...and,sincewe'renotusingDjango'sbuilt-inpermissions,#unregistertheGroupmodelfromadmin.admin.site.unregister(Group)


settings.py

AUTH_USER_MODEL='index.UserProfile'


需要删除数据库,重写建立。