Testing image upload

53 views
Skip to first unread message

Andrew Wang

unread,
May 20, 2020, 3:40:02 PM5/20/20
to Django REST framework
I'm using a serializer that only has serializer.ImageField inside an APIView, but every time I upload an image with APIRequestFactory AND APIClient, I always get back the error: {'file': [ErrorDetail(string='Upload a valid image. The file you uploaded was either not an image or a corrupted image.', code='invalid_image')]}

This is my test:

from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
file = File((Path().cwd().parent / "server/public/hi.jpg").open('rb'))
uploaded_file = SimpleUploadedFile('hi.jpg', file.read(), content_type="image/jpg")

request = arf.post(
    "/api/v1/profile/picture/",
    data={"file": uploaded_file},
    format="multipart"
)
request.META["HTTP_CONTENT_DISPOSITION"] = "attachment; filename=hi.jpg"
response = view(request)
assert response.status_code == 200, f"Response {response.data}"

I've tried every SO answer I could find... Not a single one worked for me. When I tested this view on my iOS client, it works perfectly fine.
class ServerUploadPicView(APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request):
        serializer = PictureSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response()
Again, the serializer only has the field "file" and it uses serializer.ImageField(). I have to use the serializer since just using a file upload parser configured only for images didn't work for me.

Sorry if this sounded brash. I'm just extremely frustrated... So thank you!

AW

unread,
May 20, 2020, 3:41:09 PM5/20/20
to Django REST framework
Oh and the SO question that I asked earlier, too... that has both the APIClient and APIRequestFactory: https://stackoverflow.com/questions/61920477/drf-upload-image-unittest-with-debian-buster-docker

AW

unread,
May 20, 2020, 8:15:00 PM5/20/20
to Django REST framework
Ok I see my mistake: it was the parser class. It was a part of the remnants of my APIView that I used to test with Postman.
Reply all
Reply to author
Forward
0 new messages