'is_superuser'是此函数的无效关键字参数

时间:2018-06-29 09:32:43

标签: django django-rest-framework

我使用了Django restframework。

要实现自定义用户模型,我使用AbstractBaseUser。

models.py代码在下面。

[models.py]

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, email, password, is_staff, is_admin, is_active, is_superuser, **extra_fields):
        now = timezone.now()
        if not username:
            raise ValueError('Username must be set')
        email = self.normalize_email(email)
        user = self.model(username=username, email=email, 
                        is_staff=is_staff, is_admin=is_admin,
                        is_active=is_active, is_superuser=is_superuser,
                        date_joined=now, **extra_fields)

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

    def create_user(self, username, email, password, **extra_fields):
        return self._create_user(username, email, password, False, False, True, False, **extra_fields)

    def create_superuser(self, username, email, password, **extra_fields):
        return self._create_user(username, email, password, True, True, True, True, **extra_fields)

class User(AbstractBaseUser):
    USER_TYPE_CHOICES = (
        ('django', 'Django'),
        ('facebook', 'Facebook'),
        ('google', 'Google')
    )

    user_type = models.CharField(
        max_length=20,
        choices=USER_TYPE_CHOICES,
        default='Django'
    )
    email = models.CharField(max_length=100, null=False)
    username = models.CharField(max_length=20, unique=True)
    phone = models.CharField(max_length=12)

    # Default Permission
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    date_joined = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'username'
    objects = UserManager()
    REQUIRED_FIELDS = ['email']

    def get_full_name(self):
        pass

    def get_short_name(self):
        pass

    @property
    def is_superuser(self):
        return self.is_admin

    @property
    def is_staff(self):
       return self.is_admin

    def has_perm(self, perm, obj=None):
       return self.is_admin

    def has_module_perms(self, app_label):
       return self.is_admin

    @is_staff.setter
    def is_staff(self, value):
        self._is_staff = value

当我创建超级用户时,

它抛出TypeError: 'is_superuser' is an invalid keyword argument for this function

也许我认为我的代码中没有与is_superuser相关的函数,但我不知道该怎么做。

对此有什么解决办法吗?

谢谢。

1 个答案:

答案 0 :(得分:3)

看起来像is_superuser字段被具有相同名称的属性覆盖。您应该重命名is_superuser属性以解决错误:

@property
def is_superuser_property(self):
    return self.is_admin