32

Using django 1.8, I'm observing something strange. Here is my javascript:

function form_submit(){
  var form = $('#form1_id');
  request = $.post($(this).attr('action'), form.serialize(), function(response){
     if(response.indexOf('Success') >= 0){
        alert(response);
     }
  },'text')
  .fail(function() {
    alert("Failed to save!");
  });
  return false;
}

and here are the parameters displayed in views.py

print request.POST
<QueryDict: {u'form_4606-name': [u''], u'form_4606-parents': [u'4603', u'2231', u'2234']}>

but I cannot extract the parents:

print request.POST['form_4606-parents']
2234

Why is it just giving me the last value? I think there is something wrong with the serialization, but I just cannot figure out how to resolve this.

max
  • 9,708
  • 15
  • 89
  • 144

5 Answers5

66

From here

This is a feature, not a bug. If you want a list of values for a key, use the following:

values = request.POST.getlist('key')

And this should help retrieving list items from request.POST in django/python

Windsooon
  • 6,864
  • 4
  • 31
  • 50
  • 1
    Wroked great although I'm confused as to why. This requires me to write a code that says if key is 'parents' then val=request.POST.getlist(key) otherwise val=request.POST.getl(key) – max Sep 20 '16 at 02:21
  • 1
    @max (and others) - From the linked ticket - "The reasoning behind this is that an API method should consistently return either a string or a list, but never both. The common case in web applications is for a form key to be associated with a single value, so that's what the [] syntax does. getlist() is there for the occasions (like yours) when you intend to use a key multiple times for a single value." – Sayse Apr 21 '17 at 10:12
10

The function below converts a QueryDict object to a python dictionary. It's a slight modification of Django's QueryDict.dict() method. But unlike that method, it keeps lists that have two or more items as lists.

def querydict_to_dict(query_dict):
    data = {}
    for key in query_dict.keys():
        v = query_dict.getlist(key)
        if len(v) == 1:
            v = v[0]
        data[key] = v
    return data

Usage:

data = querydict_to_dict(request.POST)

# Or

data = querydict_to_dict(request.GET)
mazurekt
  • 193
  • 2
  • 10
4

You can use getlist method

data = request.POST.getlist('form_4606-parentspass_id','')
1

This can occur when accidentally posting JSON data with the content-type multipart/form-data, rather than application/json.

I hit this situation when using the Django test HTTP client to create requests against a JSON API and calling:

data = {'a': [1, 2, 3]}
client.post('/api/endpoint/', data=my_data)

rather than:

data = {'a': [1, 2, 3]}
client.post('/api/endpoint/', data=my_data, content_type='application/json')
Ben Sturmfels
  • 1,303
  • 13
  • 22
0

The simplest way

{**request.GET}

{**request.POST}

or, if you use djangorestframework

{**request.query_params}
Den Avrondo
  • 89
  • 1
  • 6