Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Python | Sessions framework using django

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Prerequisites: Django Installation | Introduction to Django

Sessions framework can be used to provide persistent behaviour for anonymous users in the website.Sessions are the mechanism used by Django for you store and retrieve data on a per-site-visitor basis.Django uses a cookie containing a special session id.

To enable the session in the django, you will need to make sure of two things in :

  1. MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activated
  2. INSTALLED_APPS has ‘django.contrib.sessions’ added.

  3. # Application definition

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

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. 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 !")

To see the work done till 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

  1. Add and update the code in the index view function/li>
  2. Update the about view function

  3. 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)


My Personal Notes arrow_drop_up
Last Updated : 24 Jun, 2019
Like Article
Save Article
Similar Reads
Related Tutorials