0

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

bSr
  • 1,410
  • 3
  • 16
  • 30

2 Answers2

1

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
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
1

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

JPG
  • 82,442
  • 19
  • 127
  • 206
  • Worked! it's my mistake I was using the name 'file' instead of 'image' as field name when passing the image to the postman. – bSr Mar 10 '18 at 10:44