Open In App

Python | Sessions framework using django

Last Updated : 07 Nov, 2023
Like Article

The sessions framework can be used to provide persistent behavior for anonymous users on the website. Sessions are the mechanism used by Django for you to store and retrieve data on a per-site-visitor basis. Django uses a cookie containing a unique session ID.

Django Sessions

So let’s understand what a is session in Django and how to use sessions. Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It keeps data on the server side and abstracts the sending and receiving of cookies. Now that we have some basic understanding of the session let’s figure out how to use session in Django.

How to use session in Django

First, enable Session in Django. To enable the session in Django, you will need to make sure of two things in

MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activate
INSTALLED_APPS has ‘django.contrib.sessions’ added.


# Application definition

After enabling the session, the session database table has to create and to do this run the following command:

Also, ensure that the django.contrib.sessions app is included in the INSTALLED_APPS list:


    # ...
    # ...

python syncdb

After running previous command and if it didn’t find any errors then later run the command given below to finally reflect the changes saved onto the migration file onto the database.

python migrate

Now once sessions are created, then testing of the cookies has to be done.

Configure Session Storage

By default, Django uses a database-backed session storage. You can configure it in your settings file. For example, to use the database-backed session storage

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

If you prefer using cache-based sessions (which is often faster), you can configure it like this:

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

Additionally, configure the cache settings in your settings file:


    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '',

Using Sessions

In, set the test cookie in the index view, and test the cookie in your about view.


from django.shortcuts import render
from django.http import HttpResponse
from .models import Album
def home(request) :
    a = Album.objects.all()
    return render(request, "dhun/home.html ", {"Album":a})
def index(request) :
    num_authors = Author.objects.count()
    num_visits = request.session.get( 'num_visits', 0)
    request.session ['num_visits'] = num_visits + 1
    context ={
        'num_instances available':num_instances_available,
def about(request):
    LANGUAGE_CODE ='en-us '
    if request.session.test_cookie_worked():
        print ("Cookie Tested !")

Now, First run the localhost through this command.

python runserver

Then Open http://localhost:8000/ in the browser. Visit the index page then visit the about page. The “Cookie Tested!” will be printed out to the console.

To know how many times the site has been visited.You have to do following two things In

  • Add and update the code in the index view function/li>
  • Update the about view function


from django.shortcuts import render
from django.http import HttpResponse
from .models import Album
def home(request):
    a = AIbum. objects.all()
    return render(request, "dhun/home.html", {"album":a})
def index(request):
    visits = int(reques.COOKIES.get('visits', '0'))
    response = HttpResponse(template.render(context))
    if request.COOKIES.has_key('last_visit'):
        last_visit = request. COOKIES [ ' last_visit']
        last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S") "
        curr_time =
        if (curr_time—last_visit_time).days > O:
            response.set_cookie( 'visits ', visits + 1)
            response. set_cookie( ' last_visit',
        else :
            response.set_cookie( ' last_visit',
        return response
def about(request) :
    context = RequestContext(request)
    if request.COOKIES.has_key(' visits '):
        v = request.COOKIES [' visits ']
    else :
        v = 0
    return render_to_response('music/about.html', { 'visits':v}, context)

Session Expiry

By default, Django sessions expire when the user’s browser is closed. You can configure session expiry by setting the SESSION_COOKIE_AGE setting in your For example, to set a session timeout of 30 minutes:

SESSION_COOKIE_AGE = 1800  # 30 minutes (in seconds)

That’s it! You can now use the Django sessions framework to manage user-specific data across your web application. Remember to handle session data carefully, especially if it’s sensitive information or related to user authentication.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads