Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle request.GET with multiple variables for the same parameter in Django

In a Django view you can access the request.GET['variablename'], so in your view you can do something like this:

myvar = request.GET['myvar'] 

The actual request.GET['myvar'] object type is:

<class 'django.http.QueryDict'> 

Now, if you want to pass multiple variables with the same parameter name, i.e:

http://example.com/blah/?myvar=123&myvar=567

You would like a python list returned for the parameter myvar, then do something like this:

for var in request.GET['myvar']:     print(var) 

However, when you try that you only get the last value passed in the url i.e in the example above you will get 567, and the result in the shell will be:

5 6 7 

However, when you do a print of request.GET it seems like it has a list i.e:

<QueryDict: {u'myvar': [u'123', u'567']}> 

Ok Update: It's designed to return the last value, my use case is i need a list.

from django docs:

QueryDict.getitem(key) Returns the value for the given key. If the key has more than one value, getitem() returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python's standard KeyError, so you can stick to catching KeyError

QueryDict.getlist(key) Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn't exist. It's guaranteed to return a list of some sort.

Update: If anyone knows why django dev's have done this please let me know, seems counter-intuitive to show a list and it does not behave like one. Not very pythonic!

like image 760
ismail Avatar asked Oct 11 '10 21:10

ismail


People also ask

What is request method == post in Django?

method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).

How do I pass multiple parameters in URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".


2 Answers

You want the getlist() function of the GET object:

request.GET.getlist('myvar') 
like image 177
AndrewF Avatar answered Sep 20 '22 19:09

AndrewF


Another solution is creating a copy of the request object... Normally, you can not iterate through a request.GET or request.POST object, but you can do such operations on the copy:

res_set = request.GET.copy() for item in res_set['myvar']:     item ... 
like image 29
FallenAngel Avatar answered Sep 20 '22 19:09

FallenAngel