首页 > 代码库 > django user模块改写
django user模块改写
示例一:继承AbstractBaseUser,AbstractBaseUser只有三个字段password,last_login,is_active,以及需要复习的两个方法
def get_full_name(self): raise NotImplementedError()def get_short_name(self): raise NotImplementedError()
改写例子如下:
import refrom time import timezonefrom django.contrib.auth.models AbstractBaseUser, BaseUserManagerfrom django.core import validatorsclass 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 uclass 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"
配置外键的例子:
django user模块改写
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。