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
PythonINSTALLED_APPS=['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]
2. Include SessionMiddleware in MIDDLEWARE
PythonMIDDLEWARE=['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 ourdatabase. But we can change the storage engine using theSESSION_ENGINEsetting insettings.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 usingMemcached):
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'sviews.py:
Pythonfromdjango.shortcutsimportrenderfromdjango.httpimportHttpResponsedefindex(request):request.session.set_test_cookie()num_visits=request.session.get('num_visits',0)request.session['num_visits']=num_visits+1returnHttpResponse(f"Visit count:{request.session['num_visits']}")defabout(request):ifrequest.session.test_cookie_worked():print("Cookie Tested!")request.session.delete_test_cookie()returnHttpResponse("About page")
Now, First run the localhost through this command.
python manage.py runserver
Visithttp://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 is7and 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 pageAdvanced: Session Expiry Settings
By default, session data lasts until the browser is closed. You can customize this by setting theSESSION_COOKIE_AGEsetting in app'ssettings.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