How to delete a session key outside of a view?
I'm retrieving a session outside of a view by its session_key
then I'm trying to delete a key from it like the following but it's not working:
from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
my_session = SessionStore(session_key=my_session_key)
del my_session["foo"]
# also tried this but not working either:
my_session.delete("foo")
The session store does not save the new state eagerly. A view often does not add/modify/remove one key, but several ones. So typically you save the session at the end of a view.
You can force updating the session store at the backend with .save()
[Django-doc], this will then update the database, or rewrite the file, or update some other backend you use for the session storage, so:
my_session = SessionStore(session_key=my_session_key)
my_session.pop('foo', None)
my_session.save()