Django Test client launches nested JSON

I have a problem very similar to Django's Querydict: weird behavior: empty POST words in one key and Unit testing Django JSON View . However, none of the questions / answers in these threads really indicate the task that I have. I am trying to use a Django test client to send a request with a nested JSON object (which works well with JSON objects with values ​​other than JSON).

Attempt # 1: Here is my initial code:

response = c.post('/verifyNewMobileUser/', {'phoneNumber': user.get_profile().phone_number, 'pinNumber': user.get_profile().pin, 'deviceInfo': {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067', 'deviceType': 'I'}}) 

As you can see, I have a nested JSON object in my request data. However, this is what the .POST request looks like:

 <QueryDict: {u'phoneNumber': [u'+15551234567'], u'pinNumber': [u'4171'], u'deviceInfo': [u'deviceType', u'deviceID']}> 

Attempt # 2: Then I tried to add the value of the content-type parameter as follows:

 response = c.post('/verifyNewMobileUser/', {'phoneNumber': user.get_profile().phone_number, 'pinNumber': user.get_profile().pin, 'deviceInfo': {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067', 'deviceType': 'I'}}, 'application/json') 

And what am I getting now for the .POST request -

 <QueryDict: {u"{'deviceInfo': {'deviceType': 'I', 'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067'}, 'pinNumber': 5541, 'phoneNumber': u' 15551234567'}": [u'']}> 

All I want to do is specify the attached dict file for my request data. Is there an easy way to do this?

+6
source share
3 answers

The following works for me (using named args):

 geojson = { "type": "Point", "coordinates": [1, 2] } response = self.client.post('/validate', data=json.dumps(geojson), content_type='application/json') 
+14
source

Your problem indicates that Django interprets your request as multipart/form-data , not application/json . Try

c.post("URL", "{JSON_CONTENT}", content_type="application/json") .

Another thing to look at is that Python represents dictionary keys / values ​​using single quotes when rendering as strings that the simplejson parser doesn't like. Store your hard-coded JSON objects as single-quoted strings, using double quotes inside to get around this ...

+6
source

My solution is as follows:

In the testing method:

 data_dict = {'phoneNumber': user.get_profile().phone_number, 'pinNumber': user.get_profile().pin, 'deviceInfo': {'deviceID': '68753A44-4D6F-1226-9C60-0050E4C00067', 'deviceType': 'I'}}) self.client.post('/url/', data={'data': json.dumps(data_dict)}) 

In view:

 json.loads(request.POST['data']) 

This sends the message ['data'] as a string. In the view, you need to load json from this line.

Thanks.

0
source

Source: https://habr.com/ru/post/918270/


All Articles