Session array/list append does not work
Posted: February 1st, 2010 | Author: Davo | Filed under: Django | Tags: append, array, Django, session | 5 Comments »I was trying to save and update some arrays inside the Django session object but it was not working at all…
The following snippet DOES NOT WORK
request.session['array'] = [] # let's create an empty array # try to append some integers... request.session['array'].append(1) request.session['array'].append(2) request.session['array'].append(3) ...
In order to solve this we need to store the array in a temporary object first.
Quick fix:
request.session['array'] = [] tmp = request.session['array'] tmp.append(1) tmp.append(2) tmp.append(3) request.session['array'] = tmp # this works now. ...

experiencing the same issue. it seems the session is updated but on next request the update is not reflected. perhaps its only for db backed sessions?
I think, you have to save the session, because for django the session has not changed.
http://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessions-are-saved
Thanks, this has been driving me nuts.
Django will only save session when the value under a key has been modified. When you write:
request.session['array'] = []
it means that the value is a reference to your array. Appending items to the array will not modify the value (the reference to array), thus django sees no reason to save the session.
There are 2 ways of fixing this:
1) Tell django to explicitly save the session:
request.session.modified = True
2) set the SESSION_SAVE_EVERY_REQUEST setting to True. Django will then save the session to the database on every single request
Thanks a lot!