y_v
y_v

Reputation: 73

Can't upload image file while testing Django

I am developing API using Django REST Framework. I have a Django model that has models.ImageField and it works just fine. But when I want to unittest creating model object, I get error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

My code:

class PlacesTest(APITestCase):

    . . .

    def test_create_place_full(self):
        . . .
        image = SimpleUploadedFile(name='test.jpg',
                                   content=open('test.png', 'rb').read(),
                                   content_type='image/jpeg')

        request = self.factory.post(reverse('place-list'),
                                    {'name': 'test_place_1',
                                     'picture': image,  
                                     })

I have tried passing string with path to image, and I've tried methods from Django testing model with ImageField to do tests, but no success.

What type should I pass to Django REST framework when adding image: file object or string with path?

How can I add real file to my tests?

Upvotes: 0

Views: 728

Answers (1)

y_v
y_v

Reputation: 73

Found solution for my problem if someone is interested:

all I needed was specifying format='multipart' in request arguments:

request = self.factory.post(reverse('place-list'),
                                {'name': 'test_place_1',
                                 'picture': self.image},
                                format='multipart')

in my project was:

REST_FRAMEWORK = {
    ...
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

so no image could be added to POST request.

Upvotes: 3

Related Questions