brsbilgic
brsbilgic

Reputation: 11833

django rest api test to upload file/image

I implemented a simple model that have an ImageField in Django Rest. It works great with Browsable API of Django Rest.

However, when I try to write test case to post a JSON, it raises error UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Below you can check test code. Basically, I open test image and pass it as JSON parameter I'm not sure why it cannot encode.

    test_image_filename = os.path.join('/vagrant/', 'test_images', 'test_image1.jpg')
    with open(test_image_filename) as image_file:
        data = {
                "location": "123, 123",
                "location_name": "location1",
                "date": datetime.datetime.now().__str__(),
                "max_attendee": 10,
                "description": "test",
                "image": image_file,
                "tags": []
            }
        response = self.client.post('/events/', data)
        print response

Upvotes: 1

Views: 1470

Answers (1)

AdelaN
AdelaN

Reputation: 3536

Ok, so I just had the exact same problem. This is how it worked for me:

    image_path = os.path.join('/vagrant/', 'test_image1.jpg')
    with open(image_path) as logo:
        encoded_logo = base64.b64encode(logo.read())
        data = {'name': 'Domus de magnum orexis, resuscitabo candidatus!', 
                'logo': encoded_logo,
                'about': 'The small planet revolutionary travels the phenomenon.'
            }
        response = self.client.post(url, data=json.dumps(data, ensure_ascii=False), content_type='application/json')

Hope this helps :)

Upvotes: 2

Related Questions