示例一:继承AbstractBaseUser,AbstractBaseUser只有三个字段password,last_login,is_active,以及需要复习的两个方法
def get_full_name(self): raise NotImplementedError() def get_short_name(self): raise NotImplementedError()
改写例子如下:
import re from time import timezone from django.contrib.auth.models AbstractBaseUser, BaseUserManager from django.core import validators class UserManager(BaseUserManager): def create_user(self, username, email=None, password=None, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() if not username: raise ValueError('The given username must be set') email = UserManager.normalize_email(email) user = self.model(username=username, email=email, is_staff=False, is_active=True, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password, **extra_fields): u = self.create_user(username, email, password, **extra_fields) u.is_staff = True u.is_active = True u.save(using=self._db) return u class Users(AbstractBaseUser): username = models.CharField(_('username'), max_length=30, unique=True, help_text=_('少于30个字符组成'),validators=[ validators.RegexValidator(re.compile('^[w.@+-]+$'), _('Enter a valid username.'), 'invalid') ]) email = models.EmailField(_('email address'), blank=True) is_staff = models.BooleanField(default=False, verbose_name='系统管理员') is_teacher = models.BooleanField('是否是教师', default=False) is_student = models.BooleanField('是否是学校', default=False) is_school_manager = models.BooleanField('是否是学校管理员', default=False) is_college_manager = models.BooleanField('是否是学院管理员', default=False) date_joined = models.DateTimeField(_('date joined'), default=0) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = "用户" verbose_name_plural = "用户" def get_full_name(self): return self.username + "-" + self.email def get_short_name(self): return self.username
嫌麻烦直接添加字段的写法,但是会带来冗余的字段,例如first_name,last_name
再在settings里配置AUTH_USER_MODEL = "profiles.KarmaUser"
配置外键的例子: