Home > Net >  How to upload multiple images in django rest framework
How to upload multiple images in django rest framework

Time:10-12

I want to upload multiple images using image model not like a nested serializer Here is my serializer

class ProjectImageSerializer(ModelSerializer):
    class Meta:
        model = ProjectImage
        fields = (
            'id',
            'file',
            'project',
        )

This is the model

class ProjectImage(models.Model):
    file = models.ImageField(
        upload_to='apps/projects/ProjectImage/file/',
    )
    user = models.ForeignKey(
        'users.User',
        on_delete=models.CASCADE,
        related_name='project_image_set',
    )
    project = models.ForeignKey(
        'Project',
        on_delete=models.CASCADE,
        related_name='image_set',
    )
    created = CreatedField()
    last_modified = LastModifiedField()

    def __str__(self):
        return basename(self.file.name)

and here is Views.py

class ProjectImageViewSet(viewsets.ModelViewSet):
    parser_classes = [
        MultiPartParser,
    ]
    queryset = ProjectImage.objects.all()
    serializer_class = ProjectImageSerializer

can anyone help me when I try with postman its selecting multiple images but posting only one

CodePudding user response:

class ProjectImageSerializer(ModelSerializer):
    class Meta:
        model = ProjectImage
        fields = (
            'id',
            'file',
            'project',
        )
        read_only_fields = ['id']
        extra_kwargs = {'file': {'required': 'True'}}

Try above code

CodePudding user response:

You can't use this serializer for uploading multiple images. You should define another serializer which accepts a list of files in one of the fields. Something like this:

def UploadSerializer(serializers.Serializer):
    images = serializers.ListField(child=serializers.ImageField())

And then implement your logic to create ProjectImage instances in the create method.

  • Related