Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django request Post json

I try to test a view, I receive a json request from the IPad, the format is:

req = {"custom_decks": [
        {
            "deck_name": "deck_test",
            "updates_last_applied": "1406217357",
            "created_date": 1406217380,
            "slide_section_ids": [
                1
            ],
            "deck_id": 1
        }
          ],
    "custom_decks_to_delete": []
}

I checked this in jsonlint and it passed.

I post the req via:

response = self.client.post('/library/api/6.0/user/'+ uuid +
'/store_custom_dec/',content_type='application/json', data=req) 

The view return "creation_success": false

The problem is the post method in view doesn't find the key custom_decks.

QueryDict: {u'{"custom_decks": [{"deck_id": 1, "slide_section_ids": [1], 
"created_date":1406217380, "deck_name": "deck_test"}], 
"custom_decks_to_delete": []}': [u'']}>

The problem is the post method in view doesn't find the key custom_decks. Because it is converting my dict to QueryDict with one key.

I appreciate all helps.

Thanks

like image 317
user3877330 Avatar asked Jul 25 '14 15:07

user3877330


People also ask

What is HttpResponse in Django?

HttpResponse (source code) provides an inbound HTTP request to a Django web application with a text response. This class is most frequently used as a return object from a Django view.


2 Answers

You're posting JSON, which is not the same as form-encoded data. You need to get the value of request.body and deserialize it:

data = json.loads(request.body)
custom_decks = data['custom_decks']
like image 179
Daniel Roseman Avatar answered Sep 27 '22 18:09

Daniel Roseman


As I was having problems with getting JSON data from HttpRequest directly with the code of the other answer:

data = json.loads(request.body)
custom_decks = data['custom_decks']

error:

the JSON object must be str, not 'bytes'

Here is an update of the other answer for Python version >3:

json_str=((request.body).decode('utf-8'))
json_obj=json.loads(json_str)

Regarding decode('utf-8'), as mention in:

RFC 4627:

"JSON text shall be encoded in Unicode. The default encoding is UTF-8."

I attached the Python link referred to this specific problem for version >3.

http://bugs.python.org/issue10976

like image 28
chuseuiti Avatar answered Sep 27 '22 19:09

chuseuiti