Question

My Ajax call has in it the data:

data: { hint: {'asdf':4} },

I feel like I should be able to access this object with

request.POST['hint'] # and possibly request.POST['hint']['asdf'] to get 4

but this error comes in the way. I look at

MultiValueDictKeyError at /post_url/
"'hint'"

When I print the post data I get strangely misformed dictionary:

<QueryDict: {u'hint[asdf]': [u'4']}>

How am I supposed to correctly pass the data, so I that I retain the same structure in Python and use it the same way I did in JS?

Was it helpful?

Solution

First, in your $.ajax call, instead of directly putting all of your POST data into the data attribute, add it into another attribute with a name like json_data. For example:

data: { hint: {'asdf':4} },

should become:

data: { json_data: { hint: {'asdf':4} } },

Now, the json_data should be converted into a plain string using JSON.stringify:

data: { json_data: JSON.stringify({ hint: {'asdf':4} }) },

This will pass the data as a string into Django that can be retrieved by:

data_string = request.POST.get('json_data')

which can be converted to a dict-like object (assuming json is imported with import json at the top):

data_dict = json.loads(data_string)

Or, without the intermediate data_string:

data_dict = json.loads(request.POST.get('json_data'))
print data_dict['hint']['asdf'] # Should print 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top