Django rest framewok 中的令牌身份验证不适用于 digitalocean,但它在我的本地运行良好

token authentication in django rest framewok is not working with digitalocean, but it is working perfectly in my local

提问人:Arif Qasemi 提问时间:11/11/2023 最后编辑:Chukwujiobi CanonArif Qasemi 更新时间:11/13/2023 访问量:34

问:

我已经在 Digital-Ocean 上部署了一个 django rest 框架项目,当我使用 postman 软件发出请求时,一切正常,但是当向下面这个请求时,它显示此错误:postgetpostTestView

字段“id”需要一个数字,但在0x7f10fecb2ed0>时得到了<django.contrib.auth.models.AnonymousUser对象

从这一行:

score = Score.objects.get(user=request.user.id)

这是 TestView :

class TestView(APIView):
    authentication_classes = [TokenAuthentication]
    def get(self, request):
        questions = Question.objects.all()
        questions_serializer = QuestionsSerializer(questions,many=True,context={'request': request})
        return Response(questions_serializer.data)
    
    def post(self, request):
        question_id = request.data.get('id')
        user_answer = request.data.get('answers')

        correct_answer = Answer.objects.filter(question=question_id, is_correct=True).values_list('answer', flat=True).first()

        if correct_answer is not None:
            if user_answer == correct_answer:
                try:
                    score = Score.objects.get(user=request.user.id)
                    print(self.user)
                    score.score += 1
                    score.save()
                except Score.DoesNotExist:
                    score = Score.objects.create(user=request.user, score=1)

                score_serializer = ScoreSerializer(score)
                return Response({'message': 'your answer was correct', 'score': score_serializer.data}, status=status.HTTP_200_OK)
            else:
                return Response({'message': 'your answer was incorrect'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'message': 'correct answer not found for this question'}, status=status.HTTP_404_NOT_FOUND)

如果我更改了这一行:

score = Score.objects.get(user=request.user.id)

对此:

score = Score.objects.get(user=1)

然后它起作用了。

我还打印了以下内容:

print(request.user)
print(request.user.id)
print(request.auth)

它们是 null,但在 My Local 中,打印了用户实例。

我想从标头中传递的令牌中获取用户,但是当我运行时,它显示null。print(request.user.id)

Django REST 部署 框架

评论

1赞 Chukwujiobi Canon 11/11/2023
当您向其发出请求时,您发布的视图不会获得身份验证。因此,显示匿名用户的错误。请参阅 TokenAuthentication

答: 暂无答案