递给Django也会产生MultiValueDictKeyErr

递给Django也会产生MultiValueDictKeyErr

本文介绍了Django:即使键存在,将AJAX POST数据传递给Django也会产生MultiValueDictKeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Ajax调用中包含数据:

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']}>

我应该如何正确传递数据,以便在Python中保留相同的结构并以与JS中相同的方式使用它?

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?

推荐答案

首先,在您的$.ajax调用中,不要直接将所有POST数据放入data属性中,而是将其添加到另一个具有名称的属性中像json_data.例如:

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} },

应成为:

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

现在,应使用JSON.stringifyjson_data转换为纯字符串:

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

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

这会将数据作为字符串传递给Django,可以通过以下方式检索:

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

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

可以转换为类似dict的对象的

(假设json是在顶部导入import json的):

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)

或者,没有中间的data_string:

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

这篇关于Django:即使键存在,将AJAX POST数据传递给Django也会产生MultiValueDictKeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:03