1

I am trying to upload images on an endpoint in postman but i'm getting the error in the screenshot below Below is my code for sake of brevity i'll only send the affected parts.

Models:

class Post(models.Model):    
    content = models.TextField() 
    image = models.ManyToManyField(PostImage,blank=True,related_name='posts_images')

class PostImage(models.Model):
    image = models.ImageField(upload_to='post-images',validators=[FileExtensionValidator(['png','jpg','gif','jpeg'])])

Serializers:

class PostImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostImage
        fields = ('image')

class PostSerializer(serializers.ModelSerializer):
    image = PostImageSerializer(many=True, required=False)
    class Meta:
        model = Post
        fields = ['content','image',]

    def create(self, validated_data):
        r_data = self.context['request'].FILES
        
        instance = super().create(validated_data)        
        if "image" in validated_data.keys():
            images = validated_data.pop('image')
        else:
            pass
        post = Post.objects.create(**validated_data)    
        instance.image.add(r_data)
        return post

Viewsets :

class PostViewSet(ModelViewSet):
    serializer_class = PostSerializer
    queryset = Post.objects.all()

Postman response

1 Answer 1

1

Refactored the create method of the serializer and it now works

def create(self, validated_data):
        request = self.context['request']
        r_data = self.context['request'].FILES
            
        post = Post.objects.create(**validated_data)
        
        if 'image' in r_data:
            post_image = PostImage.objects.create(image=r_data['image'])
            post.image.add(post_image)
        else:
            pass
        return post
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.