django session expire time
Open your Django project's settings.py file.
Locate the
SESSION_COOKIE_AGE
setting in the settings.py file.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
Save the changes to the settings.py file.
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
Save the changes to the settings.py file.
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.")
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.
Test the session expiration by observing the behavior after the specified time has passed.
Adjust the session timeout value as needed based on your application's requirements.