Making a simple counter app using request.session in Django

PythonServer Side ProgrammingProgramming

In this article, we are going to see how to make a super simple counter app, where clicking a button will add a number and it will keep doing that even if you close the tab and keep the data in session. We will get the idea of using sessions for making a simple app and how to transfer data using sessions


In, add the following lines −

from django.urls import path
from django.urls.resolvers import URLPattern
from .import views

urlpatterns = [
   path('', views.counterView, name='counter'),

Here we set up views on home url.

In, add the following lines −

from django.shortcuts import render

# Create your views here.
def counterView(request):
   if request.method == "POST" and 'count' in request.POST:
         request.session['count'] +=1
         request.session['count'] = 0
   elif request.method == 'POST' and 'reset' in request.POST:
      request.session['count'] = 0
      return render(request,'counter.html')

Here we created a POST request handler, we will send a number from frontend and save it in session's count variable. When reset is sent from the frontend, then the session count becomes 0

Now create a templates folder in app directory and create a counter.html in it and write this −

<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=devicewidth, initial-scale=1.0">
   <link href="
dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha38
G2x" crossorigin="anonymous">
         background-color: palevioletred;
      .counter form .count{
         outline: none;
         color: white;
      .counter form .reset{
         outline: none;
         background-color:rgb(50, 181, 204);
   <div class="container counter text-center" style="margintop: 150px;">
      <h1 class="display-1 text-white">
         {% if request.session.count%}
         {%endif%}</h1> <br> <br>
         <form method="post"> {% csrf_token %}
            <button name="count" class="count px-5 py-3 textwhite shadow-lg">Count</button>
<br> <br>
      <form method="post"> {% csrf_token %}
         <button name="reset" class="reset px-5 py-3 textwhite shadow-lg">Reset</button>

Here is frontend which we are rendering on home url.


Clicking the Count button will add 1 in the number and clicking the Reset button will reset the counter to 0.

Published on 26-Aug-2021 12:20:37