python - 属性错误: type object 'MyUser' has no attribute 'USERNAME_FIELD'

标签 python django

我正在 django 中构建一个自定义 User 类,用于创建注册应用程序,每次尝试 makemigrations 时我都会收到上述错误。据我所知,我的代码是每个 django 文档 here .. 我还在我的设置配置中正确放置了 AUTH_USER_MODEL 。 这是我的 models.py

`class MyUserManager(BaseUserManager):
    def create_user(self, email, 
        first_name,last_name,profile_picture,phone_no,password=None):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            first_name=first_name,
            last_name=last_name,
            profile_picture=profile_picture,
            phone_no=phone_no,
        )

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



    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        SuperUser = self.create_user(
            email,
            password=password,
        )
        SuperUser.staff = True
        SuperUser.admin = True
        SuperUser.save(using=self._db)
        return SuperUser

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name = 'email_address',
        max_length=255,
        unique=True,
        # validators=email_validator,
    )
    first_name = models.CharField(max_length=20,blank=False,null=False)
    last_name = models.CharField(max_length=20,blank=False,null=False)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number 
    must be entered in the format: '+254 ...'")
    phone_no = models.CharField(validators=[phone_regex], max_length=17, 
    blank=False)
    profile_picture = models.ImageField(upload_to='media/',blank=False)
    # email_validator = EmailValidator(message='Invalid email 
    # address',code=None,whitelist=None)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name','last_name','phone_no','profile_picture']
    # Email & Password are required by default
    def get_full_name(self):
        return self.email
    def get_short_name():
        return self.email
    def __str__(self):
        return self.email
    def has_perm(self,perm,obj=None):
    #does user have a specific permission
        return True
    def has_module_pers(self,app_label):
    #does user have permissions to view the app 'app_label'
        return True
    @property
    def is_admin(self):
        return self.is_admin
    @property
    def is_active(self):
        return self.is_active


# hook in the New Manager to our Model
class MyUser(AbstractBaseUser):
    ...
    objects = MyUserManager()
`

最佳答案

创建自定义用户模型

class User(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

CustomUser 的官方文档

你是: - 扩展 Django 用于用户模型的基类。

  • 删除用户名字段。
  • 将电子邮件字段设为必填且唯一。
  • 列出项目告诉 Django 您将使用电子邮件字段作为 USERNAME_FIELD
  • 从 REQUIRED_FIELDS 中删除电子邮件字段 设置(它会自动包含为 USERNAME_FIELD)

Source Link

关于python - 属性错误: type object 'MyUser' has no attribute 'USERNAME_FIELD' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51308530/

相关文章:

django - 按对象的 date_created 属性对来自不同模型的查询集对象列表进行排序

python - 向数据库添加新模型实例时 Django 中的 ProgrammingError,可能出了什么问题?

python - seetings.py 或 docker 中的数据库配置错误

python - 在 Django 中运行 syncdb 时出现异常

python - Google App Engine 应用到私有(private)云

python - 通过 sys.set_trace 访问 Python 解释器的数据栈

django - 在 Django 中将 JSON 数据从响应传递到请求

python - NumPy/PyTorch 提取图像子集

python - 'tuple'对象没有属性 'clip'

python - 如何实现固定长度的空间金字塔池化层?