Session array/list append does not work

Posted: February 1st, 2010 | Author: Davo | Filed under: Django | Tags: , , , | 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.
...

5 Comments on “Session array/list append does not work”

  1. 1 keith fitzgerald said at 12:58 pm on August 27th, 2010:

    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?

  2. 2 Yufiel said at 9:48 am on September 16th, 2010:

    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

  3. 3 Tommy Mooney said at 8:53 pm on September 20th, 2010:

    Thanks, this has been driving me nuts.

  4. 4 Pawel Roman said at 2:56 pm on September 22nd, 2010:

    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

  5. 5 Lucas said at 9:51 am on March 4th, 2011:

    Thanks a lot!


Leave a Reply