我正在尝试一次发布多个表单数据(是的,它们需要作为一个发布内容进入。否,无法更改。甚至不建议进行多次提交。)并且我可以建立正确的类型对象。
convert_to_object是一个自定义函数,它将序列化的数组转换为具有正确键值对的对象
save_button.click(function(){
//Collect information
console.log("Collecting form data");
var data = {};
data.form1= convert_to_object($("[data-formtype='form1']").serializeArray());
data.form2= convert_to_object($("[data-formtype='form2']").serializeArray());
data.form3= convert_to_object($("[data-formtype='form3']").serializeArray());
var items= [];
forms_list.forEach(form_in_list=> {
items.push(convert_to_object(form_in_list.serializeArray()));
});
data.list_of_items = items;
//Send our data object to our endpoint
$.post("add", data)
.done(function(data, status){
//Success handling
})
.fail(function(data, status){
//Failure handling
})
});
这将创建正确的JavaScript对象,该对象具有正确形状的所有值,我可以将其转换为JSON字符串。
问题是,当我将此JSON字符串发送给Django时,我没有在request.POST中获得键-值对,而是将整个JSON字符串作为键,并将值作为空字符串。所以代替
<QueryDict: {
"form1":{"field1":"","field2":"","field3":""},
"form2":{"field1":"","field2":"","field3":"","field4":""},
"form3":{"field1":"","field2":"","field3":"","field4":""},
"list_of_items":[ {"item1":"", "item2":""}]
}>
我知道
<QueryDict:
'{"form1[field1]":[""],"form1[field2]":[""],"form1[field3]":[""],"form2[field1]":[""],"form2[field2]":[""],"form2[field3]":[""],"form2[field4]":[""]},"form2[field1]":["]","form2[field2]":[""],"form2[field3]":[""],"form2[field4]":[""]},"list_of_items[0][item1]":"","list_of_items[0][item2]":""}' : ''
}>
如您所见,在第二个中,整个集合被设置为键,而不是一系列键值对。
如何确保我的对象正确映射到POST查询集?
编辑
发送的JSON字符串(格式便于阅读):
{
"form1":{"field1":"","field2":"","field3":""},
"form2":{"field1":"","field2":"","field3":"","field4":""},
"form3":{"field1":"","field2":"","field3":"","field4":""},
"list_of_items":[{"item1":"", "item2":""]
}
编辑2
查看此帖子。这是与您有相同问题的人,并设法解决了该问题:Django's Querydict bizarre behavior: bunches POST dictionary into a single key
让我知道是否可行
由于@Jordan Kowal,我得以解决此问题。问题是数据是作为字符串而不是对象发送的。确保将变量保留为对象后,我能够正确加载数据。
尽管我还发现您可以将整个内容作为JSON字符串交付,然后从request.body加载,这为您提供了可以轻松处理的命令。