Search code examples
django-rest-frameworkdjango-serializerdjango-rest-viewsetsdjango-rest-framework-jwt

How to add user in perform_create viewset (django rest framework)?


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)?


Solution

  • This is because of the user field isn't a read only field. So you have to make it so.

    This DRF doc -- Specifying read only fields describes well about it

    In your case, specifying read_only_fields in your serializer's Meta class will solve the problem :)

    class CommentSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comment
            fields = '__all__'
            read_only_fields = ('user',) # change is here <<<