AttributeError:类型对象“ MyUser”没有属性“ USERNAME_FIELD”

时间:2018-07-12 14:41:05

标签: python django

我正在django中构建一个自定义User类,以用于创建注册应用程序,每次尝试进行迁移时,我都会不断遇到上述错误。据我所知,我的代码是根据django文档here编写的。 我还将AUTH_USER_MODEL正确放置在我的设置配置中。 这是我的模型。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()
`

3 个答案:

答案 0 :(得分:0)

您的代码包含格式错误的多行注释

#email_validator = EmailValidator(message='Invalid email address',code=None,whitelist=None)

该注释的第二行实际上未注释,因此地址后的单引号打开了一个字符串,该字符串似乎包含该类的其余部分,并在结尾处的流浪单引号处关闭了。

答案 1 :(得分:0)

创建自定义用户模型

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

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

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

CustomUser的官方文档

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

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

Source Link

答案 2 :(得分:0)

在创建自定义用户模型时,USERNAME_FIELD必须为唯一

因此,您只能像Roshan所说的那样创建唯一的电子邮件字段,但是在某些情况下,某些服务的电子邮件可能不是唯一的。

所以我更喜欢仅创建一个uuid字段,并将其设置为USERNAME_FIELD,

class User(AbstractBaseUser):
    uid = models.UUIDField(
        default=None,
        blank=True,
        null=True,
        unique=True,
    )

    USERNAME_FIELD = "uid"