Making a simple counter app using request.session in Django

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

Example

In urls.py, 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 views.py, 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:
      try:
         request.session['count'] +=1
      except:
         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 −



   
   
   
   Counter
   


   
   
     

         {% if request.session.count%}          {{request.session.count}}          {%else%}          0          {%endif%}



         
{% csrf_token %}                      


     
{% csrf_token %}                
   

Here is frontend which we are rendering on home url.

Output

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

Updated on: 2021-08-26T12:22:43+05:30

755 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements