我有自定义的用户模型,这是模型:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
class AccountManager(BaseUserManager):
def create_user(self, username=None, password=None, **kwargs):
account = self.model(username=username)
account.set_password(password)
account.is_stuff = False
account.save()
return account
def create_superuser(self, username, password, **kwargs):
account = self.create_user(username, password, **kwargs)
account.is_admin = True
account.is_staff = True
account.save()
return account
class Account(AbstractBaseUser):
username = models.CharField(max_length=40, unique=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
initialized = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
objects = AccountManager()
然后当我尝试获取所有用户的列表时,它会抛出AttributeError: 'Account' object has no attribute 'is_staff'
。
class GetUserList(ListAPIView):
permission_classes = (permissions.IsAdminUser,)
queryset = Account.objects.all()
serializer_class = AccountSerializer
答案 0 :(得分:4)
IsAdminUser
调用is_staff
,它是在django的auth用户模型上定义的。因此,如果您有自己的自定义用户模型,则还需要为此提供实现
在django的A
课程中,它是一个BooleanField,您可以看到here
答案 1 :(得分:0)
在定义自己的权限后解决了问题:
class IsAdminUser(permissions.BasePermission):
def has_permission(self, request, view):
return request.user.is_admin
然后
class GetUserList(ListAPIView):
permission_classes = (IsAdminUser,)
queryset = Account.objects.all()
serializer_class = AccountSerializer
答案 2 :(得分:0)
正如@Sayse和@Daniel指出的那样,您可以通过将is_staff
字段添加到自定义用户模型来解决此问题:
is_staff = models.BooleanField(_('staff status'),default=False)
(这对我有用)
答案 3 :(得分:0)
对我来说,这是通过将这两个模型添加进来的
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
然后在管理器中
def create_user(self, email, 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),
)
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.
"""
user = self.create_user(
email,
password=password,
)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
这在Django 3中有效。
我在Dev.to
答案 4 :(得分:0)
我将Django的版本更改为较早的版本 'pip install django == 2.2' 对我有用。