User模型有不少功能,驗證什麼的,重寫須要知足下面的功能(基本上寫註釋的地方都是須要的)django
開始:app
建立一個重寫user的app, 記得註冊app加密
startapp newauthspa
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, User # AbstractBaseUser封裝了密碼加密存儲, PermissionsMixin封裝了各類n對n關係,ex:user and permission class UserManager(BaseUserManager): """ 實現User的 object功能 """ def _create_user(self, telephone, username, password, **kwargs): user = self.model(telephone=telephone, username=username, **kwargs) user.set_password(password) user.save() return user # 建立普通用戶 def create_user(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = False return self._create_user(telephone, username, password, **kwargs) # 建立超級用戶 def create_superuser(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = True return self._create_user(telephone, username, password, **kwargs) class User(AbstractBaseUser, PermissionsMixin): """ 重寫User模型 """ telephone = models.CharField(max_length=11, unique=True) username = models.CharField(max_length=50) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) gender = models.IntegerField(default=0) # 0: 未知 1:男 2:女 data_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'telephone' # authenticate進行驗證的字段 REQUIRED_FIELDS = ['username'] # createsuperuser命令輸入的字段,django默認要求輸入密碼,因此不須要指定password EMAIL_FILED = 'email' # 指定發送郵箱 objects = UserManager() # 存入model中 def get_full_name(self): return self.username def get_short_name(self): return self.username
最後須要在settings申明使用改寫的 User模型code
# AUTH_USER_MODEL是django內置的屬性,使用該屬性去指定User模型
AUTH_USER_MODEL = 'xfzauth.User' # 重寫的User模型
就能夠makemigrates blog
migrateget
映射表了io