How to clear all session variables without getting logged out

Siecje picture Siecje · Apr 16, 2013 · Viewed 39.7k times · Source

I am trying to clear all of the session variables but not logout the current user.

user = request.session.get('member_id', None)
request.session.flush()
request.session.modified = True
request.session['member_id'] = user
request.session.modified = True

Will this also affect other users of the site?

Answer

shacker picture shacker · Apr 17, 2015

As of Django 1.8, any call to flush() will log out the user. From the docs:

Changed in Django 1.8: Deletion of the session cookie is a behavior new in Django 1.8. Previously, the behavior was to regenerate the session key value that was sent back to the user in the cookie.

If you want to be able to delete keys but keep the user logged in, you'll need to handle it manually:

for key in request.session.keys():
    del request.session[key]

Or just delete the specific keys that are of concern:

del request.session['mykey']