CustomUser没有属性“对象”

时间:2019-07-18 11:40:39

标签: django python-3.x django-models django-rest-framework

我正在使用jwt auth系统,当我填写该字段时,它会轻松返回jwt令牌,但是如果我想使用此令牌创建配置文件,它会显示

  

CustomUser没有属性“对象”

我的 users / models.py

class CustomUser(AbstractBaseUser, PermissionsMixin):
   email = models.EmailField(max_length=40, unique=True)
   first_name = models.CharField(max_length=30, blank=True)
   last_name = models.CharField(max_length=30, blank=True)
   date_joined = models.DateTimeField(default=timezone.now)

   object = UserManager()

   USERNAME_FIELD = 'email'

   def save(self, *args, **kwargs):
      super(CustomUser, self).save(*args, **kwargs)
      return self

user / views.py

class CreateUserAPIView(APIView):
permission_classes = (AllowAny,)

def post(self, request):
    user = request.data
    serializer = UserSerializer(data=user)
    serializer.is_valid(raise_exception=True)
    serializer.save()

    try:
        email = request.data['email']
        password = request.data['password']

        user = CustomUser.object.get(email=email, password=password)
        if user:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_details = {}
                user_details['id'] = "%s" % (user.id)
                user_details['token'] = token
                user_logged_in.send(sender=user.__class__,
                                    request=request, user=user)
                return Response(user_details, status=status.HTTP_200_OK)

            except Exception as e:
                raise e
        else:
            return Response(status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'error': 'please provide a email and a password'}
        return Response(res)

使用此代码,我得到一个令牌,但是使用此令牌,我无法创建配置文件

profile / models.py

class Profile(TimeModel):
   user = models.OneToOneField('user.CustomUser', on_delete=models.CASCADE)
   first_name = models.CharField(max_length=30, null=True)
   last_name = models.CharField(max_length=30, null=True)
   birthdate = models.DateTimeField(null=True)
   image = models.ImageField(upload_to='path', null=True)

   def __str__(self):
     return self.user.email

这是我到目前为止尝试过的。我试图寻找解决方案,但无法解决,但没有一个解决了我的问题。我该如何解决这个问题。任何帮助,将不胜感激!谢谢!

PS 在序列化程序文件中,没有其他覆盖的功能,它仅包含模型名称和Profile模型字段

2 个答案:

答案 0 :(得分:2)

您正在使用自定义管理器,并将其分配给CustomUser模型中的object而不是objects

class CustomUser(AbstractBaseUser, PermissionsMixin):
    ...
    objects = UserManager()
    ...

此外,您的查询集应使用CustomUser。对象 .get(...)我认识到的另一件事是,您覆盖了{{1}中的save方法},但您并没有在此做任何特定的事情,因此无需重写该方法。

答案 1 :(得分:1)

我认为您的代码中有错字-应该是objects

user = CustomUser.objects.get(email=email, password=password)