[Fixed]-How to clear all session variables without getting logged out

26๐Ÿ‘

โœ…

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']
๐Ÿ‘คshacker

15๐Ÿ‘

In versions of django < 1.8, session.flush deletes the session data and regenerates the session key. It wonโ€™t affect other users since session keys are unique.

๐Ÿ‘คNgenator

6๐Ÿ‘

You can clear keys you have set in the django session, but to do so without logging the user out takes a little bit of trickiness; request.session.flush() logs the user out. And request.session = {} in deleting all keys in the session dictionary will also log the user out.

Thus, to clear out keys without logging the user out, you have to avoid keys that begin with an underscore character. The following code does the trick:

for key in list(request.session.keys()):
  if not key.startswith("_"): # skip keys set by the django system
    del request.session[key]
๐Ÿ‘คtalkingtoaj

5๐Ÿ‘

As an improvement to shackerโ€™s1 in Python 2.x dict.keys() returns a list copy of the keys of a dictionary, in Python 3.x it instead returns an iterator. changing the size of an iterator is unwise. For an version safe implementation casting to list will prevent any size issues

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

My previous answer suggested the use of dict.viewkeys() but it will also return an iterator in python 3.x.

๐Ÿ‘คRobert Wisner

2๐Ÿ‘

request.session internally uses cookies. And when a user requests some url of the site, only cookies present on that userโ€™s machine is sent to the server. So, request.session is always tied to the current user.

So, this in no way will affect other users of the site.

Also this will not log out the current user, because you are using flush() which will delete the old session and create a new session and this new session would be associated with the current user.

flush() internally uses clear(), delete() and create().

In the response this new sessionโ€™s key would be sent as a cookie and in subsequent requests this new session would continue working normally.

๐Ÿ‘คAkshar Raaj

2๐Ÿ‘

session_keys = list(request.session.keys())
    for key in session_keys:
        del request.session[key]
๐Ÿ‘คAdamG

Leave a comment