0
0
Djangoframework~5 mins

Session expiry behavior in Django

Choose your learning style9 modes available
Introduction

Sessions help remember who a user is while they browse your site. Session expiry makes sure this memory doesn't last forever, keeping things safe and tidy.

You want users to log in again after some time for security.
You want to clear user data after they close the browser.
You want to limit how long a user stays logged in without activity.
You want to control session length for different parts of your site.
Syntax
Django
SESSION_COOKIE_AGE = 1209600  # Time in seconds (default 2 weeks)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

# To set session expiry in a view:
request.session.set_expiry(value)

# value can be:
# - an integer (seconds)
# - 0 (expire on browser close)
# - None (use global settings)

SESSION_COOKIE_AGE sets how long sessions last by default.

SESSION_EXPIRE_AT_BROWSER_CLOSE makes sessions end when the browser closes if set to True.

Examples
This sets all sessions to expire after 1 hour.
Django
SESSION_COOKIE_AGE = 3600  # Sessions last 1 hour
Sessions will end when the user closes their browser.
Django
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
This view sets the session to expire 5 minutes after the last activity.
Django
def my_view(request):
    request.session.set_expiry(300)  # expire after 5 minutes
    return HttpResponse('Session set to 5 minutes')
This makes the session end when the browser closes, overriding global settings.
Django
def my_view(request):
    request.session.set_expiry(0)  # expire on browser close
    return HttpResponse('Session expires on browser close')
Sample Program

This example has two views. One sets a session that expires in 10 seconds and stores a user name. The other checks if the session still has the user.

Django
from django.http import HttpResponse

def set_short_session(request):
    # Set session to expire after 10 seconds
    request.session.set_expiry(10)
    request.session['user'] = 'Alice'
    return HttpResponse('Session set for 10 seconds')

def check_session(request):
    user = request.session.get('user', 'No session')
    return HttpResponse(f'User in session: {user}')
OutputSuccess
Important Notes

Session expiry counts from the last user activity, so it resets if the user keeps interacting.

Setting expiry to 0 means the session ends when the browser closes, which is good for sensitive data.

Always test session expiry behavior in your browser's private mode to avoid cached sessions.

Summary

Sessions remember users but should not last forever for safety.

You can control session length globally or per user with set_expiry().

Use session expiry to improve security and user experience.