Open In App

Sessions framework using django - Python

Last Updated : 17 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Keep user data persistent between HTTP requests.
  • Store this data server-side (in the database, cache or file).
  • Identify users using a session ID saved as a cookie in their browser.

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 Django

First, create a Django project:

Django Introduction and Installation
Creating a 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):

SESSION_ENGINE = 'django.contrib.sessions.backends.db'

2. To use cache-based sessions:

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

You’ll also need to configure caching (example using Memcached):

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',

'LOCATION': '127.0.0.1:11211',

}

}

Step 3: Creating a Visit Counter Using Sessions

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.

django10
Current visit count = 7

Notice that in the above snapshot, the current visit count is 7 and if we refresh the page it should increase by 1.

django11
Visit count after refreshing = 8

Navigate to the /about page, it should render “Cookie Tested Succesfully”.

django12
Snapshot of /about page

Advanced: Session Expiry Settings

By 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


Next Article
Practice Tags :

Similar Reads