### 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 ###
def index(request):
...
num_authors = Author.objects.count() # The 'all()' is implied by default.
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
'num_visits': num_visits,
}
# Render the HTML template index.html with the data in the context variable.
return render(request, 'index.html', context=context)