Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an object in nested serializer giving an error of bad request "owner is required"?

This is my first time dealing with nested serializers and it gives me an error "owner" is required while creating a post. Why is that?

class CreatePostView(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser]

    def post(self, request, *args):
        user = request.user
        data = request.data
        data['owner'] = user
        print(data)
        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

PostSerializer:

class PostSerializer(serializers.ModelSerializer):
    owner = UserSerializer()
    comments = CommentSerializer(many=True, read_only=True)
    class Meta:
        model= Post
        fields = ("id", "img", "posted_at", "caption", "owner", "comments")

Post model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Post(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
    img = models.ImageField(upload_to=post_img_url, default="default.jpg", max_length=200)
    caption = models.CharField(max_length=100, null=True, blank=True)
    posted_at = models.DateTimeField(auto_now_add=True, blank=True)

    objects = models.Manager()
    current_user_posts = CurrentUsersPosts.as_manager()

    class Meta:
        ordering = ("-posted_at",)

    def __str__(self):
        return f"{self.img} posted by {self.owner} at {self.posted_at}"

console:

<QueryDict: {‘owner’: [], ‘img’: [<InMemoryUploadedFile:
treeHouse.jpg (image/jpeg)>]}> Bad Request: /api/posts/upload/
[02/Aug/2022 11:14:01] "POST /api/posts/upload/ HTTP/1.1" 400 37

>Solution :

You should not modify request.data, do this instead:

if serializer.isvalid():
    serializer.save(owner=request.user)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading