Django test client encoding of JSON Booleans

180 views
Skip to first unread message

Daniel Smith

unread,
Feb 21, 2014, 5:44:14 PM2/21/14
to django...@googlegroups.com
I'm using Django version 1.5.5. Here is a short snippet of the test I'm writing:

from django.test import TestCase

class MyTest(TestCase):

  def my_test(self):
    url = ... location of my view ...
    self.client.post(url, data={'active': False}, format='json')


The problem I'm running into is that when I inspect request.POST inside my view, I get: {'active': [u'False']}. The workaround I have right now is to use json.loads(request.raw_post_data), but I'm wondering if this is a bug or if I am just missing something. Any help would be greatly appreciated.

Camilo Torres

unread,
Feb 22, 2014, 10:56:21 AM2/22/14
to django...@googlegroups.com
Hello,

The test client is not converting the data to json.

1. In your test module, you must convert the data to json and tell the correct content-type application/json:
json_data = json.dumps({'active': False})
data = self.client.post(path=url, data=json_data, content_type='application/json')

I notice that you use a format='json' parameter to post; I can't find anything about that parameter in the documentation or the code. You should use content_type='application/json' instead.

2. In the views module, you should parse the json data:
    if request.method == 'POST':
        body = request.body.decode('UTF-8')
        json_data = json.loads(body)
        print('views 12', json_data['active'])

Kindly note that you should be using request.body instead of the deprecated raw_post_data.

Regards,
Camilo

Daniel Smith

unread,
Feb 24, 2014, 2:37:44 PM2/24/14
to django...@googlegroups.com
Thank you very much for the help. So it sounds like I just have to suck it up and call json.loads() on request.body. 

The 'format=json' thing is related to also using the TastyPie test client. I've tried both and forgot where that parameter was used.

Thanks,
Daniel

Tom Evans

unread,
Feb 24, 2014, 5:20:17 PM2/24/14
to django...@googlegroups.com
On Mon, Feb 24, 2014 at 7:37 PM, Daniel Smith
<daniel...@schrodinger.com> wrote:
> Thank you very much for the help. So it sounds like I just have to suck it
> up and call json.loads() on request.body.
>
> The 'format=json' thing is related to also using the TastyPie test client.
> I've tried both and forgot where that parameter was used.
>
> Thanks,
> Daniel

Possibly - but the thing you DO have to do is give JSON data *TO* the
test client, instead of a python dictionary which will get converted
to a string (which, by chance, is JSON decodable).

Cheers

Tom
Reply all
Reply to author
Forward
0 new messages