views:

163

answers:

2

I have a simple Django view that just returns URL parameters, but if I use the same parameter key multiple times, I cannot seem to access it. Consider the following set-up:

urls.py:

(r'^header/$',header)

View function:

def header(request)
    return render_to_response('header.html',locals(),mimetype='text/plain')

Template:

{{ request.GET }}
{% for key,val in request.GET %}
{{ key }} : {{ val }}
{% endfor %}

URL:

  • http://mysite/header/?item=1&item=2

Response:

<QueryDict: {u'item': [u'1', u'2']}>

item : 2

Should the 'item' entry have the value of '1,2' or "['1','2']"? Notice what the full GET returns. How do I get both values?

+1  A: 

It's returning the multiple values in a list. In the back-end, you can just check to see if the variable is a list or not and then treat the cases accordingly. It looks like there's some logic to return the last value assigned to a key if you coerce it to a string like you're doing.

Tom
Is there no mechanism to do this from the template?
kzh
@kzh - You don't want to do that in the template, you want to do that in the view.
Dominic Rodger
@Dom - I generally wouldn't, but I was curious if Django had a mechanism for this, that's all.
kzh
Does the lists "property" mentioned in Lance McNearney's comment work? Check for value.lists and loop over that if it exists.
Tom
+4  A: 

Take a look at the documentation for the QueryDict which is used to hold the GET/POST attributes.

Specifically:

QueryDict is a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple="multiple">, pass multiple values for the same key.

You probably want to use QueryDict.lists():

q = QueryDict('a=1&a=2&a=3')
q.lists()
[(u'a', [u'1', u'2', u'3'])]
Lance McNearney