参考https://docs.djangoproject.com/zh-hans/2.2/topics/auth/customizing/
1 from django.db import models 2 from django.contrib.auth.models import ( 3 BaseUserManager, AbstractBaseUser 4 ) 5 6 7 class MyUserManager(BaseUserManager): 8 def create_user(self, email, date_of_birth, password=None): 9 """ 10 Creates and saves a User with the given email, date of 11 birth and password. 12 """ 13 if not email: 14 raise ValueError('Users must have an email address') 15 16 user = self.model( 17 email=self.normalize_email(email), 18 date_of_birth=date_of_birth, 19 ) 20 21 user.set_password(password) 22 user.save(using=self._db) 23 return user 24 25 def create_superuser(self, email, date_of_birth, password): 26 """ 27 Creates and saves a superuser with the given email, date of 28 birth and password. 29 """ 30 user = self.create_user( 31 email, 32 password=password, 33 date_of_birth=date_of_birth, 34 ) 35 user.is_admin = True 36 user.save(using=self._db) 37 return user 38 39 40 class MyUser(AbstractBaseUser): 41 email = models.EmailField( 42 verbose_name='email address', 43 max_length=255, 44 unique=True, 45 ) 46 date_of_birth = models.DateField() 47 is_active = models.BooleanField(default=True) 48 is_admin = models.BooleanField(default=False) 49 50 objects = MyUserManager() 51 52 USERNAME_FIELD = 'email' 53 REQUIRED_FIELDS = ['date_of_birth'] 54 55 def __str__(self): 56 return self.email 57 58 def has_perm(self, perm, obj=None): 59 "Does the user have a specific permission?" 60 # Simplest possible answer: Yes, always 61 return True 62 63 def has_module_perms(self, app_label): 64 "Does the user have permissions to view the app `app_label`?" 65 # Simplest possible answer: Yes, always 66 return True 67 68 @property 69 def is_staff(self): 70 "Is the user a member of staff?" 71 # Simplest possible answer: All admins are staff 72 return self.is_admin
在setting中添加
1 AUTH_USER_MODEL = 'customauth.MyUser'