为什么我的FormData对象过帐到django列表字典中? [英] Why is my FormData object POSTing into a django dictionary of lists?

查看:51
本文介绍了为什么我的FormData对象过帐到django列表字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过ajax FormData 对象向Django后端提交表单时,我的 request.POST 似乎是一本字典,其值是列表,而不是字符串.即,我希望这样:

When I submit a form via an ajax FormData object to my Django back-end, my request.POST seems to be a dictionary whose values are lists, not strings. I.e., I expect this:

In [1]: request.POST
Out[1]: {'somekey': 'somevalue', ...}

相反,我得到这个:

In [2]: request.POST
Out[2]: {'somekey': ['somevalue'], ...}

这是我的提交方式:

var form = document.forms["my-form"]
//note, all of #my-form's inputs are type="hidden" if it makes a difference...
var fd = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/my-view/', true);
xhr.onload = function(){
    if(xhr.status == 200){
       //doStuff();...
    }
}
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(fd);

很明显,我可以遍历我的request.POST字典并将这些列表转换为字符串,然后再尝试使用数据实例化django Form 对象(出于验证目的),但是我感到出了点问题.为什么我的 FormData 对象变成一个列表字典(显然不能原样使用它来创建有效的Django Form )?

Obviously, I could loop through my request.POST dictionary and turn those lists into strings before trying to instantiate a django Form object with the data (for validation purposes), but I get a feeling that something is wrong. Why is my FormData object turning into a dictionary of lists (which obviously can't be used as-is to create a valid django Form)?

推荐答案

A

A QueryDict like request.POST can handle multiple items for each key. This is the case whether it's an ajax request or not.

不用担心,您不必预处理数据.如果您使用 request.POST 实例化表单,则该表单会很好地处理它.

Don't worry about it, you don't have to preprocess the data. If you instantiate your form with request.POST, the form will handle it fine.

如果您要手动处理帖子数据,请注意,有一个 getlist 方法可用于检索列表.以文档中的示例为基础:

If you are manually handling post data, note that there is a getlist method that you can use to retrieve the list. To build on the example from the docs:

>>> from django.http import QueryDict
>>> q = QueryDict('a=1&a=2&c=3')
>>> q
<QueryDict: {'a': ['1', '2'], 'c': ['3']}>
>>> q['a']  # gets the last item
u'2'
>>> q.getlist('a')  # gets the list
[u'1', u'2']
>>> q['c']  # gets the last (and only) item
u'3'
>>> q.getlist('c')  # gets the list (which contains a single item)
[u'3']

这篇关于为什么我的FormData对象过帐到django列表字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆