The Wayback Machine - https://web.archive.org/web/20240907000945/https://www.geeksforgeeks.org/python-sessions-framework-using-django/
Open In App

Python | Sessions framework using django

Last Updated : 07 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 settings.py:

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

Python3




# Application definition
INSTALLED APPS = [
'dhun',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.securitY.SecuritYMiddleware',
'django.contrib.sessions.middleware.SessionMiddLeware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMidd1eware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


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:

Python3




INSTALLED_APPS = [
    # ...
    'django.contrib.sessions',
    # ...
]


python manage.py 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 manage.py 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:

Python3




CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}


Using Sessions

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

Python3




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()
    request.session.set_test_cookie()
    num_visits = request.session.get( 'num_visits', 0)
    request.session ['num_visits'] = num_visits + 1
    context ={
        'num_books':num_books,
        'num_instances':num_instances,
        'num_instances available':num_instances_available,
        'num_authors':num_authors,
        'num_visits':num_visits,
    }
         
def about(request):
    LANGUAGE_CODE ='en-us '
    TIME_ZONE ='UTC'
    if request.session.test_cookie_worked():
        print ("Cookie Tested !")
        request.session.delete_test_cookie()


Now, First run the localhost through this command.

python manage.py 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 views.py:

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

Python3




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 = datetime.now()
        if (curr_time—last_visit_time).days > O:
            response.set_cookie( 'visits ', visits + 1)
            response. set_cookie( ' last_visit', datetime.now())
        else :
            response.set_cookie( ' last_visit', datetime.now())
        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 settings.py. 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.



Previous Article
Next Article

Similar Reads

Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
15+ min read
Implement Token Authentication using Django REST Framework
Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works by providing token in exchange for exchanging use
2 min read
How to Create a basic API using Django Rest Framework ?
Django REST Framework is a wrapper over the default Django Framework, basically used to create APIs of various kinds. There are three stages before creating an API through the REST framework, Converting a Model's data to JSON/XML format (Serialization), Rendering this data to the view, and Creating a URL for mapping to the views.This article revolv
4 min read
Creating and Using Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization,
3 min read
Rendering Data-Frame to html template in table view using Django Framework
In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use 'render' and 'HttpResponse' functions to manipulate the data inside the DataFrame. Sample DataFrame:
3 min read
Joke Application Project Using Django Framework
Django is a high-level Python-based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. Today we will create a Joke app in Django. Installation pip3 install dj
2 min read
Voting System Project Using Django Framework
Project Title: Pollster (Voting System) web application using Django frameworkType of Application (Category): Web application. Introduction: We will create a pollster (voting system) web application using Django. This application will conduct a series of questions along with many choices. A user will be allowed to give voting for that question by s
12 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counter app is a straightforward tool designed for easy
6 min read
OTP Verification in Django REST Framework using JWT and Cryptography
In this article, we'll explore how to implement OTP verification in Django REST Framework using JWT and cryptography. We will guide you through the process of setting up your Django application to support OTP-based authentication, demonstrate how to integrate JWT for secure token management and show how cryptographic techniques can enhance the over
6 min read
Django REST Framework Installation
Django REST Framework can be installed via pip package similar to Django installation. Since Django REST Framework is a wrapper over default Django Framework, to install it, Django should be installed already. Now to install rest framework follow the below process. Prerequisites Python Pip Django How to install Django REST Framework To install Djan
1 min read
Boolean Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
String Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Core arguments in serializer fields - Django REST Framework
Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer
6 min read
URL fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
File upload Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
ListField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
IPAddressField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
Numeric fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Date and time fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, date, etc. Then, you would need AutoField, Ch
7 min read
Choice Selection Fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
ModelSerializer in serializers - Django REST Framework
ModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model's data to JS
7 min read
HiddenField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
JSONField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
DictField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
4 min read
Serializer Fields - Django REST Framework
Serializer comes with some fields (entries) that process data in and out of the serializer in Django REST Framework. The very motive of Serializing is to convert DB data to a datatype that can be used by javascript. For example, if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need
13 min read
JWT Authentication with Django REST Framework
JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in Django. Modules re
2 min read
How to pass data to javascript in Django Framework ?
Django is a python framework for web development which works on jinja2 templating engine. When data is rendered along with the template after passing through views.py, that data becomes static on the html file along which it was rendered. As django is a backend framework, hence to use the power of python to use that data dynamically requests need t
3 min read
Top 10 Reasons to Choose Django Framework For Your Project
When it comes to choosing a new language or framework for a project what matters to most of the developers? Simplicity? Reliability? Built-in packages to save a lot of time? Security? Rapid development? Community support? Versatility? or what?â€Ķ.. Well, we can’t deny that we always want a language or framework that can fulfill most of the requiremen
9 min read
Model Fieldname restrictions in Django Framework
A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating or any other stuff related to database. Django model
2 min read
Serializer Relations - Django REST Framework
Serialization is one of the most important concepts in RESTful Webservices. It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serializers to serialize object instances, and the serializ
15+ min read
Article Tags :
Practice Tags :