自定义Django用户模型失败

时间:2018-11-06 13:00:45

标签: django

**嗨 我正在尝试自定义django默认用户。应用迁移工作正常。但是,当我尝试创建超级用户时出现错误。您能告诉我为什么会出现此错误吗?

******************** self.UserModel._default_manager.db_manager(数据库).create_superuser(** user_data)   在create_superuser中,文件“ /home/gravityns/PycharmProjects/dev/shop/models.py”,第54行     user.is_staff = True AttributeError:无法设置属性


# accounts.models.py

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
from django.core.validators import RegexValidator


class UserManager(BaseUserManager):
    def create_user(self, username, password, email):
        """
        Creates and saves a User with the given email and password.
        """
        if not username:
            raise ValueError('Users must have a username')
        if not email:
            raise ValueError('Users 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_staffuser(self, username, password, email):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            username,
            email,
            password,

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

    def create_superuser(self, username, password, email):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            username,
            email,
            password

        )
        user.is_staff = True
        user.is_admin = True
        user.save(using=self._db)
        return user


USERNAME_REGEX = '^[a-zA-Z0-9.@+-]*$'

class User(AbstractBaseUser):
    username = models.CharField(max_length=255, validators=[
        RegexValidator(regex= USERNAME_REGEX,
                       message = 'Username must be Alphanumeric or any of the following: ". @ + -"')],
                                unique=True

                                )
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )

    created_at = models.DateField(auto_now_add=True, blank=True)

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

    is_staff = models.BooleanField(default=False) # a admin user; non super-user

    # notice the absence of a "Password field", that's built in.

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email'] # Email & Password are required by default.

    objects = UserManager()

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.is_staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.is_admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.is_active

3 个答案:

答案 0 :(得分:0)

您正在用自定义属性覆盖普通的is_staff属性。您需要重命名这些属性,以便它们不会与AbstractBaseUser已经实现的东西冲突。在这里查看该类如何实现is_staff和其他类:https://github.com/django/django/blob/master/django/contrib/auth/models.py#L288

答案 1 :(得分:0)

用户模型上的字段为User.is_staff,名称为@property。因此,无法通过user_instance.is_staff = True设置模型对象的属性。

您可以将is_staff作为字段或类属性,而不能同时使用。

答案 2 :(得分:0)

您为PRIOR id = parent_idis_staffis_active定义了不必要的属性。但是这些都是已经字段,具有完全相同的名称。因此,当您尝试设置is_superuser时,Python将访问您的属性,并尝试“设置”该属性,而不是字段。

没有理由这样做。您需要定义这些属性的唯一原因是,您是否想禁止自己设置字段。但是您不想这样做。 (或者,如果您根本不需要字段,但希望基于某些自定义逻辑来设置值,但同样,除非定义了自定义设置器,否则您将无法设置它们。)

删除所有这三个属性。