如何在Django-Rest-Framework中设置当前user_id?

ehxuflar  于 2022-12-27  发布在  Go
关注(0)|答案(2)|浏览(156)

所有的答案都是关于如何在类中使用generics.ListCreateAPIView参数设置当前用户。但我只是使用APIView,我使用函数"post"来发布数据。
Can someone tell me how can I set a current user_id in this file. And do I need to add something in the serializers.py too?

    • 查看次数. py**
class CreateVideo(APIView):
    permissions_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, format=None):
        print(request.data)
        serializer = VideoSerializer(data=request.data)
        user=self.request.user.id
        if serializer.is_valid():
            serializer.save(user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I created a variable "user" with self.request.user.id in it and then I passed it to the serializer.save(user). And when I created new video on the frontend side. It me gave a Bad Reuest Error.

w8rqjzmb

w8rqjzmb1#

您可以用途:

serializer.save(user=request.user)
eqqqjvef

eqqqjvef2#

您需要传递request.user而不是self.request.user

  • 确认用户是否登录?
def post(self, request, format=None):
        print(request.data)
        serializer = VideoSerializer(data=request.data)
        user=request.user
        if serializer.is_valid():
            serializer.save(user=user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Res

错误(串行器.错误,状态=状态. HTTP_400_BAD_REQUEST)

相关问题