Home > Enterprise >  Creating an object in nested serializer giving an error of bad request "owner is required"
Creating an object in nested serializer giving an error of bad request "owner is required"

Time:08-02

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:

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

CodePudding user response:

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

if serializer.isvalid():
    serializer.save(owner=request.user)
  • Related