[Solved]-Django session expires at browser close OR after time


As Jiaaro suggested in this answer you can use SESSION_EXPIRE_AT_BROWSER_CLOSE and set a timestamp on session at each request and add a custom Middleware to handle the inactivity.



From docs https://docs.djangoproject.com/en/1.8/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions

Some browsers (Chrome, for example) provide settings that allow users to continue browsing sessions after closing and re-opening the browser. In some cases, this can interfere with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting and prevent sessions from expiring on browser close. Please be aware of this while testing Django applications which have the SESSION_EXPIRE_AT_BROWSER_CLOSE setting enabled.


Sessions expire when the user closes the browser:

This requirement implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.


Sessions expire after a period of inactivity:

SESSION_COOKIE_AGE is the age of session cookies, in seconds.
Default: 1209600 (2 weeks, in seconds)


You should set these option on your setting/__init__.py


Search engine cache make sure then the session will be closed when TOGETHER with SESSION_EXPIRE_AT_BROWSER_CLOSE = TRUE

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'


By default, SESSION_EXPIRE_AT_BROWSER_CLOSE is set to False, which means session cookies will be stored in users’ browsers for as long as SESSION_COOKIE_AGE. Use this if you don’t want people to have to log in every time they open a browser.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.

Leave a comment