Alsomt all the answers are talking about how to set current user in the class with paraemter generics.ListCreateAPIView. But I'm just using APIView and I'm using function "post" to post the data.
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?
views.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.
CodePudding user response:
You can use:
serializer.save(user=request.user)
CodePudding user response:
You need Pass request.user
instead of self.request.user
.
-make sure user logged in or not ??
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
ponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)