Search code examples
pythondjangodictionarykeyerror

KeyError 0 when trying to traverse session dictionary in Django


I'm trying to traverse the session variable to print out all of its contents.

for s in request.session:
    print str(s)

The resulting error is as follows

KeyError at /<app name>/searchResults/
0

With the following traceback.

/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
    115. response = callback(request, *callback_args, **callback_kwargs)

/<path to django app>/views.py
    106. for s in request.session:

/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py in __getitem__
    46 return self.__session[key]

Any idea what '0' means as an error? I've never seen this kind of thing before.


Solution

  • The correct way to iterate over the session's values is request.session.itervalues() - the base session class exposes the same key/value/item options as a standard dictionary. I am unsure so far where it's getting the values your for loop is finding, but it's not the values.