使用AbstractBaseUser的Django用户模型

时间:2018-07-17 20:59:49

标签: django django-models

所以伙计们,我正在尝试在Django中实现自定义用户模型。我遇到的问题是说“没有这样的列:UserAcc_mycustomuser.is_staff”。我尝试阅读Django文档,但仍然无法使它工作

model.py

from django.db import models
from django.core.validators import RegexValidator

from django.contrib.auth.models import (

    BaseUserManager, AbstractBaseUser
)
USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$'

# Create your models here.
class MyUserManager(BaseUserManager):
  def create_user(self, username, email, password= None):
      if not email:
         raise ValueError('User must have an email address')
      user = self.model(
           username = username,
           email = self.normalize_email(email)
      )
      user.set_password(password)
      user.save(using=self._db)
      return user

  def create_superuser(self, username, email, password=None):
      user = self.create_user(
          username, email, password=password
      )
      user.is_admin= True
      user.is_staff= True

      user.save(using= self._db)
      return user


class MyCustomUser(AbstractBaseUser):
    username = models.CharField(max_length= 30, validators = 
    [RegexValidator(regex = USERNAME_REGEX,message='Username must be alphanumeric or contain numbers', code='invalid_username')] , unique = True)

      email = models.EmailField(
        max_length=255,
        unique = True,
        verbose_name= 'Email_Address'
)
   is_admin = models.BooleanField(default=False)
   is_staff = models.BooleanField(default=False)


objects = MyUserManager()

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']

1 个答案:

答案 0 :(得分:0)

也许它需要进行迁移并将其应用于数据库

python manage.py makemigrations
python manage.py migrate