5

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?

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
mgPePe
  • 5,677
  • 12
  • 52
  • 85

1 Answers1

11

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
huu
  • 7,032
  • 2
  • 34
  • 49