How can I delete a session variable in django?

my session variable is "trash":

cart = {'8': ['a'], ['b'], '9': ['c'], ['d']}

      

if i want to delete the entire variable of my cart i just do this in python:

del request.session['cart']

      

but i just want to remove key "8" so i try this but it doesn't work:

del request.session['cart']['8']

      

however if i print request.session ['cart'] ['8'] and get a, b

+3


source to share


2 answers


A django session object can only persist when it changes. But since you are modifying the object in the session, the session object does not know that it has changed and hence it cannot save.

To let the session object know its modified usage:

request.session.modified = True

      

From the django docs:

https://docs.djangoproject.com/en/dev/topics/http/sessions/



When Sessions Are Saved By default, Django only saves the session when the session has changed, that is, if any of its dictionary values ​​have been assigned or removed:

# Session is modified. 
request.session['foo'] = 'bar'

# Session is modified. 
del request.session['foo']

# Session is modified. 
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session. request.session['foo']['bar'] = 'baz' 

      

In the latter case above For example, we can explicitly tell the session object that it has been modified by setting the changed attribute on the session object:

  request.session.modified = True

      

To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST parameter to True. If set to True, Django will persist the session to the database on every single request.

Note that a session cookie is only sent when a session is created or modified. If SESSION_SAVE_EVERY_REQUEST is True, a session cookie will be sent on every request.

Likewise, the expired portion of the session cookie is updated every time the session cookie is sent.

The session is not saved if the response status code is 500.

+5


source


Mine request.session['cart']

was a list like this:[u'2', u'2', u'1']

So this worked for me:



list_cart  = request.session['cart']
list_cart.remove('2')

      

result: [u'2', u'1']

+1


source







All Articles