类型对象'User'没有属性'objects',Django

11

我正在尝试通过JWT令牌从API获取用户列表,因此我生成了令牌,并使用电子邮件和密码尝试使用令牌进行GET请求,但是我收到了以下错误:

File "/home/tboss/Desktop/environment/liveimages/backend/venv/lib/python3.7/site-packages/rest_framework_simplejwt/authentication.py", line 111, in get_user
user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
rest_framework.request.WrappedAttributeError: type object 'User' has no attribute 'objects'

我已经创建了自定义用户如下:

views.py:

from users.models import User
from rest_framework import viewsets
from rest_framework.decorators import api_view, permission_classes, authentication_classes  
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.status import  (
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
HTTP_200_OK)
from . import serializers
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication, SessionAuthentication



class UserViewSet(viewsets.ModelViewSet):
queryset = User.object.all()
serializer_class = serializers.UserSerializers

settings.py:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
    'rest_framework_simplejwt.authentication.JWTAuthentication',
   
),
'DEFAULT_PERMISSION_CLASSES':(
    'rest_framework.permissions.IsAuthenticated',
)
    
}

错误

我正在使用 User.object,它运行良好,但是这个错误来自于 JWT。

User models.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models  import Token


class UserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
    if not email:
        raise ValueError('user must have email address')
    now = timezone.now()
    email = self.normalize_email(email)
    user = self.model(
        email=email,
        is_staff=is_staff,
        is_active=True,
        is_superuser=is_superuser,
        last_login=now,
        date_joined=now,
        **extra_fields
    )
    user.set_password(password)
    user.save(using=self._db)
    return user
def create_user(self, email, password, **extra_fields):
    return self._create_user(email, password, False, False, **extra_fields)

def create_superuser(self, email, password, **extra_fields):
    user=self._create_user(email, password, True, True, **extra_fields)
    user.save(using=self._db)
    return user

class User(AbstractBaseUser, PermissionsMixin):
   email = models.EmailField(max_length = 100, unique = True)
   First_Name = models.CharField(max_length = 100, null = True, blank = True)
   Last_Name = models.CharField(max_length = 100, null = True, blank = True)
  is_staff = models.BooleanField(default = False)
  is_superuser = models.BooleanField(default = False)
  is_active = models.BooleanField(default = True)
  last_login = models.DateTimeField(null = True, blank = True)
  date_joined = models.DateTimeField(auto_now_add=True)

  USERNAME_FIELD = "email"
  EMAIL_FIELD = "email"
  REQUIRED_FIELD = []

  object = UserManager()

def get_absolute_url(self):
    return "/users/%i/" % (self.pk)

我已经添加了编辑。 - afk
它是 .objects 而不是 .object - Willem Van Onsem
请展示您的“用户”模型。 - dirkgroten
1
@afk,你的INSTALLED_APPS中有rest_framework.authtoken这个包吗? - Nalin Dobhal
4
你拼写经理的名字错了:object = UserManager() 应该改为 objects - dirkgroten
显示剩余5条评论
4个回答

35

我刚刚遇到了同样的“Token not User”错误。

你需要将'rest_framework.authtoken'添加到你的INSTALLED_APPS中,然后别忘了运行'manage.py migrate'。

这对我来说解决了问题。


2

我刚遇到了同样的错误,我在settings.py文件中添加了以下几行。

SIMPLE_JWT = {
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,
}

同时将以下行添加到 settings.py 文件中。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_simplejwt' #new line
]

同时运行以下命令:python manage.py migrate 现在,它已经可以使用了。


0

检查一下这段代码

    objects = MyUserManager()

没有 object=...


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community
这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - Sachin

0

我用过这个,对我很有效

python manage.py migrate


问题已经在评论中得到解决,而你的回答对于问题本身来说有些泛泛而谈。 - Ícaro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接