Last Updated : 11 Jul, 2025
Django sessions let us store data for each user across different pages, even if they’re not logged in. The data is saved on the server and a small cookie (sessionid) is used to keep track of the user.
A session stores information about a site visitor for the duration of their visit (and optionally beyond). It allows us to:
This is useful for tracking shopping carts, user preferences, form data and anonymous analytics like page visits.
In this article, we'll build a simple Django app that tracks and displays the number of visits using sessions. Below is the step by step guide on how to create it and demonstrate how the sessions work:
Step 1: Enabling Sessions in DjangoFirst, create a Django project:
After creating the project, enable sessions in Django by ensuring two things in settings.py:
1. Add 'django.contrib.sessions' to INSTALLED_APPS Python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
2. Include SessionMiddleware in MIDDLEWARE Python
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', # Must be here
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', # Must be after sessions
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2. Creating the Sessions Table
To initialize the session table in your database:
python manage.py migrate
This applies all necessary migrations, including the creation of the sessions table.
Step 2: Configuring Session Storage (Optional)By default, Django stores session data in our database. But we can change the storage engine using the SESSION_ENGINE setting in settings.py file to store cache based sessions.
1. To use database-backed sessions (default):2. To use cache-based sessions:SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
You’ll also need to configure caching (example using Memcached):
Step 3: Creating a Visit Counter Using SessionsCACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
Let’s now build a simple visit counter to demonstrate how sessions work paste the code below in app's views.py:
Python
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
request.session.set_test_cookie()
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
return HttpResponse(f"Visit count: {request.session['num_visits']}")
def about(request):
if request.session.test_cookie_worked():
print("Cookie Tested!")
request.session.delete_test_cookie()
return HttpResponse("About page")
Now, First run the localhost through this command.
python manage.py runserver
Visit http://localhost:8000 in your browser. Refresh the index page multiple times and you’ll see the visit count increasing.
Current visit count = 7Notice that in the above snapshot, the current visit count is 7 and if we refresh the page it should increase by 1.
Visit count after refreshing = 8Navigate to the /about page, it should render “Cookie Tested Succesfully”.
Snapshot of /about page Advanced: Session Expiry SettingsBy default, session data lasts until the browser is closed. You can customize this by setting the SESSION_COOKIE_AGE setting in app's settings.py.
For example, to set a session timeout of 30 minutes:
SESSION_COOKIE_AGE = 1800 # 30 minutes (in seconds)
You can also force the session to expire on browser close:
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4