1

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
1
  • Should have been the file contents, I think, rather than the open file object Commented Aug 27, 2014 at 15:51

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

The submitted data was not a file. Check the encoding type on the form. I tried this and the error shows up.

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.