Modifying Dictionary in Django Session Does Not Modify Session

Viewed 14473

I am storing dictionaries in my session referenced by a string key:

>>> request.session['my_dict'] = {'a': 1, 'b': 2, 'c': 3}

The problem I encountered was that when I modified the dictionary directly, the value would not be changed during the next request:

>>> request.session['my_dict'].pop('c')
3
>>> request.session.has_key('c')
False
# looks okay...
...
# Next request
>>> request.session.has_key('c')
True
# what gives!
3 Answers

As the documentation states, another option is to use

SESSION_SAVE_EVERY_REQUEST=True

which will make this happen every request anyway. Might be worth it if this happens a lot in your code; I'm guessing the occasional additional overhead wouldn't be much and it is far less than the potential problems from neglecting from including the

request.session.modified = True

line each time.

I'm not too surprised by this. I guess it's just like modifying the contents of a tuple:

a = (1,[2],3)
print a
>>> 1, [2], 3)

a[1] = 4
>>> Traceback (most recent call last):
...  File "<stdin>", line 1, in <module>
...  TypeError: 'tuple' object does not support item assignment

print a
>>> 1, [2], 3)

a[1][0] = 4
print a
>>> 1, [4], 3)

But thanks anyway.

Related