I am making a post via Jquery ajax that looks like this:
$.ajax({
type: 'POST',
url: "/sandbox/read_demands/",
data: {
"partner_ref": "PH",
"return_field": ["summary", "details"]
},
success: [read_demands_response],
dataType: 'json'
});
I then recieve the data on the server-side with a simple Django view that only prints request.POST into a log. The data then looks like this:
{u'return_field[]': [u'summary', u'details'], u'partner_ref': [u'PH']}
As you can see, the key ‘return_field’ has become ‘return_field[]’ and the value for ‘partner_ref’ is now a list. What on earth is going on? Am I missing something complected obvious in the jquery post that causes my data to be malformed or is do you think this error comes from somewhere else? I am trying to rule-out different possibilities until I can find the cause of the problem.
This is jquery 1.8.2 and Django 1.4 btw.
The first one is just jQuery being jQuery. For reasons best known to themselves, the makers of jQuery believe that PHP is the only way to write server-side applications, and PHP expects fields that have more than one value to have the
[]suffix – so if you don’t provide one, it’ll add it. You just have to use it like that in Django.However, the second one is not an error. It’s just how a Django QueryDict works: any value can have multiple items, so they’ll always be represented as a list. However,
request.POST['partner_ref']will correctly give the single value. And in fact to access both values of the other key, you’ll need to dorequest.POST.getlist('return_field[]').Edit: as pointed out in the comments,
$.ajaxSettings.traditional = true;fixes the jQuery issue.