### Sessions expire when the user closes the browser ###
### add this line in settings.py ###
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
---------### Sessions expire after a period of inactivity ###------------------
### Fisrt way ###
### 1- set a timestamp in the session on every request ###
request.session['last_activity'] = datetime.now()
### 2- add a middleware to detect if the session is expired ###
### Note => search how to add a middleware ###
class SessionExpiredMiddleware:
def process_request(request):
last_activity = request.session['last_activity']
now = datetime.now()
if (now - last_activity).minutes > 10:
# Do logout / expire session
# and then...
return HttpResponseRedirect("LOGIN_PAGE_URL")
if not request.is_ajax():
# don't set this for ajax requests or else your
# expired session checks will keep the session from
# expiring :)
request.session['last_activity'] = now
---------### Sessions expire after a period of inactivity ###------------------
### second way ###
### add these lines in settings.py ###
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 10 # set just 10 seconds to test
SESSION_SAVE_EVERY_REQUEST = True # whenever you make new request, It saves the session and updates timeout to expire
### A session expired when you close the browser even if SESSION_COOKIE_AGE set ###
### Only when you are idle for more than 10 seconds, the session will expire ###