GRS
GRS

Reputation: 3104

Django REST: Auth user is not passed to the serialiser error - Field is required

I'm not sure what I'm doing wrong, but the authenticated user is not registered in the serialiser.

Models.py

class Post(models.Model):
    posted_by = models.ForeignKey('auth.User', on_delete=models.CASCADE)


    def save(self, *args, **kwargs):
        super(Post, self).save(*args, **kwargs)

Serializers.py

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = '__all__'

    def create(self, validated_data):
        post = Post.objects.create(**validated_data)
        # extra code to add images

views.py

class PostViewSet(viewsets.ModelViewSet):

    serializer_class = PostSerializer

    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
        IsOwnerOrReadOnly, )

    def perform_create(self, serializer):
        serializer.save(posted_by=self.request.user)

I don't understand why serializer.save(posted_by=self.request.user) doesn't work as intended. It should pass the required information about the field.

When I do a POST request, I get the error that

{
    "posted_by": [
        "This field is required."
    ]
}

I think it's something to do with the create method in the serialiser. For some reason, posted_by is not present in validated_data (or something similar). I would like to know what exactly is happening behind the scenes.

Upvotes: 1

Views: 37

Answers (1)

vishes_shell
vishes_shell

Reputation: 23564

just specify posted_by as read only field.

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = '__all__'
        read_only_fields = ('posted_by', )

Upvotes: 2

Related Questions