Reputation: 2392
I want to store a Python list in my session variable and edit it on subsequent view calls. I just did this (in a view):
if 'x' not in request.session:
request.session['x'] = []
request.session['x'].append('test')
This only works on the first try, i.e. the session will actually contain ['test']
under dict key 'x'
after the first time this view is called. However, when I try to do this a second time, the list is updated (as I can see when debugging) but the value is not persisted, as evidenced by debugging any subsequent calls: the value remains ['test']
long-term, instead of becoming ['test','test']
.
I have found the following step as a workaround, but I'm unsure whether I should try working around it: does this code circumvent a reasonable constraint imposed by Django ?
temp_var = request.session['x']
temp_var.append('test')
request.session['x'] = temp_var
Upvotes: 1
Views: 1321
Reputation: 14369
In Django as it is implemented the session is updated when it is changed.
This is pretty straightforward for immutable type since they are always changed by assignments and the sessions __setitem__
is called. The session knows about the change.
If you store a mutable object like your list in the session it only holds a reference to it. If the list is changed the reference stays the same. Nothing is called on the session. It will never notice the change.
So, with Djangos sessions you should always use an assignment to store or change values.
Upvotes: 4