[Fixed]-How to delete nested session data in Django?

18👍

The django session object can only save when its modified. But because you are modifying an object within session, the session object doesn’t know its being modified and hence it cant save.

To let the session object know its modified use:

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 to the session
database when the session has been modified – that is if any of its
dictionary values have been assigned or deleted:

# 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 last case of the above
example, we can tell the session object explicitly that it has been
modified by setting the modified attribute on the session object:

  request.session.modified = True

To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. When set to True,
Django will save the session to the database on every single request.

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

Similarly, the expires part of a session cookie is updated each time
the session cookie is sent.

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

1👍

My 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']

0👍

For example, putting request.session.modified = True (False by default) anywhere in test() can save(delete) nested session data as shown below. *Session is automatically saved only when top-level key’s data is modified and you can see When sessions are saved and you can see my question and my answer explaining when and where session is saved:

# "veiws.py"

from django.http import HttpResponse

def test(request):
    request.session.modified = True # Or
    del request.session['cart']['8']
    request.session.modified = True # Or
    return HttpResponse('Test')

Or, setting SESSION_SAVE_EVERY_REQUEST True in settings.py as shown below also can save(delete) nested session data:

# "settings.py"

SESSION_SAVE_EVERY_REQUEST = True

Leave a comment