当我通过ajax FormData
对象向我的Django后端提交表单时,我的request.POST
似乎是一个字典,其值是列表,而不是字符串。即,我希望如此:
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
)?
答案 0 :(得分:3)
request.POST
request.POST
可以为每个键处理多个项目。这是否是ajax请求的情况。
不用担心,您不必预处理数据。如果您使用getlist
实例化表单,表单将处理它。
如果您手动处理发布数据,请注意可以使用>>> 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']
方法检索列表。要构建文档中的示例:
{{1}}