I am trying to post several form data in one go (Yes, they need to go in as one post content. No this can not be changed. Don’t even suggest having multiple submits.) and I can build correct type of object.
convert_to_object is a custom function that converts serialized array into an object with correct key-value pairs
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
})
});
This creates correct JavaScript object that has all the values in correct shape and I can convert this to JSON string.
Issue is that when I send this JSON string to Django I don’t get key-value pairs in request.POST, instead I get the entire json string as key and value as empty string. So instead of
<QueryDict: {
"form1":{"field1":"","field2":"","field3":""},
"form2":{"field1":"","field2":"","field3":"","field4":""},
"form3":{"field1":"","field2":"","field3":"","field4":""},
"list_of_items":[ {"item1":"", "item2":""}]
}>
I get
<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]":""}' : ''
}>
As you can see, in the second one the entire set is made into key, instead of series of key-value pairs.
How do I ensure that my object gets correctly mapped out to the POST queryset?
EDIT
JSON string that is send(with formatting for easier reading):
{
"form1":{"field1":"","field2":"","field3":""},
"form2":{"field1":"","field2":"","field3":"","field4":""},
"form3":{"field1":"","field2":"","field3":"","field4":""},
"list_of_items":[{"item1":"", "item2":""]
}
EDIT 2
Screenshot of XHR (Firefox). Please ignore 501 response, that is intented response (for now)
2
Answers
Thanks to @Jordan Kowal I was able to solve the issue. Issue was that data was being send as a string, instead of an object. After making sure that the variable remains as an object, I was able to correctly load the data.
Altough I also found that you can deliver entire thing as JSON string and then load it from request.body, which gives you a dict you can easily process.
Check out this post. This is someone having the same issue as you, and managed to fix it : Django's Querydict bizarre behavior: bunches POST dictionary into a single key
Let me know if it works