Search code examples
pythondjangodjango-testing

SimpleUploadedFile won't POST


I want to pass a dictionary to a function using Client. It looks like that:

response = self.client.post(
        '/upload_image/', {'image': image, 'tags': ['orion', ]})

In my view, it's posting data to i have:

print(request.POST)
image = request.POST['image']
tags = reguest.POST['tags']

There is a MultiValueDictKeyError on request.POST['image'].

print(request.POST) shows that dictionary looks like:

<QueryDict: {'tags': ['orion']}>

image objects is:

image = SimpleUploadedFile(
            'kitties.png', b'kitties_in_boxes', 'image/png')

It's about the image object, because when I pass something else as image (For example a string) it works well.

I suppose there is another way I could test uploading images functionality, but does someone know why this doesn't works?


Solution

  • Django separates uploaded files from other submitted data. The tags key exits in request.POST, but image should be in request.FILES. From what I can see, what you're doing is the correct way to test file upload with the test client.

    More info on forms and files in django.