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']
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.
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]
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.
- How can I schedule a Task to execute at a specific time using celery?
- How can I test if my redis cache is working?
- How can I disable a model field in a django form
- How to create custom groups in django from group
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.
- Create a canonical "parent" product in Django Oscar programmatically
- Paypal monthly subscription plan settings for first day of the month and making monthly recurring payment – django python
2👍
session_keys = list(request.session.keys())
for key in session_keys:
del request.session[key]