【问题标题】:Django: passing AJAX POST data to Django yields MultiValueDictKeyError even though key existsDjango:将 AJAX POST 数据传递给 Django 会产生 MultiValueDictKeyError,即使键存在
【发布时间】:2014-06-28 23:26:45
【问题描述】:

我的 Ajax 调用中有数据:

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

我觉得我应该能够访问这个对象

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

但是这个错误来了。我看看

MultiValueDictKeyError at /post_url/
"'hint'"

当我打印帖子数据时,我得到了奇怪的错误字典:

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

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

【问题讨论】:

    标签: jquery python ajax django post


    【解决方案1】:

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

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

    应该变成:

    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')
    

    可以转换为类似字典的对象(假设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
    

    【讨论】:

    • 很有道理,谢谢!
    • 当主题是带有ajax的JSON时,django让生活变得非常艰难
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2020-07-27
    • 2018-08-04
    • 1970-01-01
    • 2012-10-09
    • 2018-06-18
    • 2012-11-13
    相关资源
    最近更新 更多