Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django QueryDict only returns the last value of a list

Tags:

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.

like image 872
max Avatar asked Sep 19 '16 03:09

max


2 Answers

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

like image 149
Windsooon Avatar answered Oct 17 '22 09:10

Windsooon


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) 
like image 26
mazurekt Avatar answered Oct 17 '22 09:10

mazurekt