Django: passing AJAX POST data to Django gives a MultiValueDictKeyError, although the key exists

There is data in my Ajax call:

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

It seems to me that I should have access to this object with

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

but this error gets in the way. I look

MultiValueDictKeyError at /post_url/
"'hint'"

When I print the message data, I get a strangely distorted dictionary:

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

How should I pass the data correctly, so that I keep the same structure in Python and use it the same way as in JS?

+4
source share
1 answer

First, in your call, $.ajaxinstead of directly putting all your POST data in an attribute data, add it to another attribute with a type name json_data. For instance:

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

should become:

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

json_data , JSON.stringify:

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

Django, :

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

dict ( , json import json ):

data_dict = json.loads(data_string)

data_string:

data_dict = json.loads(request.POST.get('json_data'))
print data_dict['hint']['asdf'] # Should print 4
+8

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


All Articles