Escher
Escher

Reputation: 5786

Why is my FormData object POSTing into a django dictionary of lists?

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', ...}

Instead, I'm getting this:

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

Here's how I submit:

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);

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)?

Upvotes: 0

Views: 1930

Answers (1)

Alasdair
Alasdair

Reputation: 309009

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

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.

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']

Upvotes: 3

Related Questions