Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Django Sign Up and login with confirmation Email | Python
Next article icon

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 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 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:

Python
fromdjango.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.

django10
Current visit count = 7

Notice that in the above snapshot, the current visit count is7and 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 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


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp