django session expire time

  1. Open your Django project's settings.py file.

  2. Locate the SESSION_COOKIE_AGE setting in the settings.py file.

  3. Set the value of SESSION_COOKIE_AGE to the desired session timeout period in seconds.

# settings.py

# Set session timeout to 30 minutes (1800 seconds)
SESSION_COOKIE_AGE = 1800
  1. Save the changes to the settings.py file.

  2. Optionally, you can configure the SESSION_SAVE_EVERY_REQUEST setting to True if you want to update the session expiration time on each request.

# settings.py

# Update session expiration on each request
SESSION_SAVE_EVERY_REQUEST = True
  1. Save the changes to the settings.py file.

  2. If you want to set a specific expiration time for a session upon creation, you can use the set_expiry method in your views.

# views.py

from django.shortcuts import render
from django.http import HttpResponse

def set_session(request):
    # Set session expiration to 1 hour (3600 seconds)
    request.session.set_expiry(3600)
    return HttpResponse("Session expiration set to 1 hour.")
  1. Make sure to handle the expiration gracefully in your application, such as by prompting the user to reauthenticate or redirecting them to the login page when the session expires.

  2. Test the session expiration by observing the behavior after the specified time has passed.

  3. Adjust the session timeout value as needed based on your application's requirements.