I want to make a "comment" table. On the table, there will be a field containing user_id that created the comment. The user related with the comment table is from Django default user model. This is the Comment model:
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
This is the Comment serializer:
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = '__all__'
This is the viewset to create new comment:
class CommentViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
I also integrate the user with django rest jwt for the authorization. This is the header & data i sent to the API.
Header:
Authorization: Bearer {jwt token}
Content-Type: application/json
body:
{ "content": "This is the comment" }
But i get this response:
{ "user": [ "This field is required." ] }
How to fix the serializer, so it will retrieve the user from the token (request.user)?