Modifying Dictionary in Django Session Does Not Modify Session

django, session

Solution

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.

Problem

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! ```

Original source