24Oct

Django Gotchas: Django’s request.GET dictionary and ‘in’

Posted by Elf Sternberg as django, programming, python

I wish I’d known this a long time ago.  Django’s request object includes a dictionary of key/value pairs passed into the request via POST or GET methods.  That dictionary, however, works in a counter-intuitive fashion.  If a URL reads http://foo.com?a=boo, then the expected content of request.GET['a'] would be 'boo', right?  And most of us who’ve used other URL parsers in the past know that http://foo.com?a=boo&a=hoo know that the expected content of request.GET['a'] would be ['boo', 'hoo'].

Except it isn’t.  It’s just 'hoo'.  Digging into the source code, I learn that in Django’s MultiValueDict, __getitem__(self, key) has been redefined to return the last item of the list.  I have no idea why.  Maybe they wanted to ensure that a scalar was always returned.  The way to get the whole list (necessary when doing an ‘in’ request) is to call request.GET.getlist('a').

Lesson learned, an hour wasted.

2 Responses to Django Gotchas: Django’s request.GET dictionary and ‘in’

Herman

March 31st, 2011 at 3:09 am

This is an important lesson, but I think the way Django does it makes more sense than other URL parsers – if you’re looking for a list of items through which to iterate, you should specifically call getlist(), otherwise only a single value is returned – and assuming that there is only one value after that point won’t get you into trouble.

Otherwise, unless you’re really careful everywhere, someone could craft an URL that has http://foo.com?a=boo&a=hoo, while you intended only a=boo. Then suddenly you’re working with a list where you expected to work with a string, can things can quite easily go awry.

Sweta

April 23rd, 2013 at 11:33 am

Thanks a ton! You saved me a lot of time

Comment Form

Subscribe to Feed

Categories

Calendar

October 2010
M T W T F S S
« Sep   Nov »
 123
45678910
11121314151617
18192021222324
25262728293031