Cannot urlencode () after storing QueryDict in session

I tried posting this to the django-users group ( http://groups.google.com/group/django-users/browse_thread/thread/8572d7f4075cfe0e ) but did not receive any answers. Maybe here I get more help.

I store request.GET in the session:

 request.session['query_string'] = request.GET 

then I get the value on another page and try to execute urlencode QueryDict:

 context['query_string'] = request.session['query_string'].urlencode() 

in my context, I get a python string representation of a QueryDict object instead of the expected key0=value0&key1=value1&... string.

If instead of QueryDict I save the urlencoded string to the session, everything works, of course:

 request.session['query_string'] = request.GET.urlencode() 

this is mistake?

+4
source share
1 answer

It's not a mistake. If you look at the definition of QueryDict (see https://github.com/django/django/blob/master/django/http/ init .py ), it explicitly says that it is immutable unless you create a copy of it.

To demonstrate this, here is what I have in my Python shell,

 >>> from django.http import QueryDict >>> q1 = QueryDict('', mutable=False) >>> q2 = QueryDict('', mutable=True) >>> q1['next'] = '/a&b/' Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/kenny/Desktop/Kreybits/locker/python/lib/python2.7/site-packages/django/http/__init__.py", line 357, in __setitem__ self._assert_mutable() File "/Users/kenny/Desktop/Kreybits/locker/python/lib/python2.7/site-packages/django/http/__init__.py", line 354, in _assert_mutable raise AttributeError("This QueryDict instance is immutable") AttributeError: This QueryDict instance is immutable >>> q2['next'] = '/a&b/' >>> q2.urlencode() 'next=%2Fa%26b%2F' 

The mutable argument is set to False by default, and since request.session['query_string'] = request.GET initialized it to an empty QueryDict to start, calling urlencode() returns only an empty string, and request.session['query_string'] = request.GET.urlencode() works because you are working with a QueryDict that has been initialized with the appropriate key / values.

0
source

All Articles