Django URL Parameter Key Used Twice
I have a simple Django vi开发者_Python百科ew 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?
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'])]
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.
精彩评论