bSr
bSr

Reputation: 1526

Django Rest Framework: Uploading a Image

I can't save the image to the image field. Error

"image": [
    "No file was submitted."
]

models.py

class MyImages(models.Model):
    name = models.CharField(max_length=255)
    image = models.ImageField(upload_to='myphoto', null=False,       max_length=255, blank=False)

views.py

class ImageList(APIView):
    parser_classes = (MultiPartParser, FileUploadParser,)

    def post(self, request):
        file_serializer = MyImageSerializer(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
            return Response(file_serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serialiser.py

class MyImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyImages
        fields = ('id', 'name', 'image')

when using postman for file upload the file name is returned in view.py instead of the file object.

I have also seen these threads but not working 1 2

Upvotes: 0

Views: 128

Answers (2)

JPG
JPG

Reputation: 88429

I couldn't find any bug in your code when I tried to reproduce the error.
Make sure that uncheck the application/json content type
enter image description here

Then the postman console will be as follows,
enter image description here

Upvotes: 1

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38922

FileUploadParser populates request.data with a file key containing uploaded file.

However, ImageSerializer needs to serialize image this from the request.

Ergo, you need to specify fields explicitly. e.g.

class ImageFileField(serializers.Field):
    def to_representation(self, obj):
        return obj.image.url

    def to_internal_value(self, data):
        return data['file']


class MyImageSerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    image = ImageFileField(source='*')

    class Meta:
        model = MyImages

Upvotes: 1

Related Questions