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

6
  • Are you using form-data option in POSTMAN ? Commented Mar 9, 2018 at 5:00
  • @JerinPeterGeorge yes Commented Mar 9, 2018 at 5:10
  • what are the headers are you sending in the request ? Commented Mar 9, 2018 at 8:32
  • @AnjaneyuluBatta I am using postman and it automatically detects the header. I no need to write header. Commented Mar 9, 2018 at 8:37
  • @bSr can you add POSTMAN screenshot too ? Commented Mar 9, 2018 at 8:59

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Worked! it's my mistake I was using the name 'file' instead of 'image' as field name when passing the image to the postman.

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.