इस लेख में, हम यह देखने जा रहे हैं कि सुपर सरल काउंटर ऐप कैसे बनाया जाता है, जहां एक बटन पर क्लिक करने से एक नंबर जुड़ जाएगा और यह ऐसा करता रहेगा, भले ही आप टैब को बंद कर दें और डेटा को सत्र में रखें। हमें एक साधारण ऐप बनाने के लिए सत्रों का उपयोग करने और सत्रों का उपयोग करके डेटा स्थानांतरित करने का विचार मिलेगा
उदाहरण
urls.py, . में निम्नलिखित पंक्तियाँ जोड़ें -
from django.urls import path
from django.urls.resolvers import URLPattern
from .import views
urlpatterns = [
path('', views.counterView, name='counter'),
] यहां हम होम यूआरएल पर व्यू सेट अप करते हैं।
views.py, . में निम्नलिखित पंक्तियाँ जोड़ें -
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')
यहां हमने एक POST अनुरोध हैंडलर बनाया है, हम फ्रंटएंड से एक नंबर भेजेंगे और इसे सेशन के काउंट वेरिएबल में सेव करेंगे। जब फ़्रंटएंड से रीसेट भेजा जाता है, तो सत्र गिनती 0 हो जाता है
अब एक टेम्पलेट बनाएं ऐप निर्देशिका में फ़ोल्डर और एक counter.html . बनाएं इसमें लिखें और इसे लिखें -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=devicewidth, initial-scale=1.0">
<title>Counter</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/
dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha38
4-
+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyT
G2x" crossorigin="anonymous">
</head>
<body>
<style>
body{
background-color: palevioletred;
}
.counter form .count{
border:none;
outline: none;
background-color:black;
color: white;
}
.counter form .reset{
border:none;
outline: none;
background-color:rgb(50, 181, 204);
}
</style>
<div class="container counter text-center" style="margintop: 150px;">
<h1 class="display-1 text-white">
{% if request.session.count%}
{{request.session.count}}
{%else%}
0
{%endif%}</h1> <br> <br>
<form method="post"> {% csrf_token %}
<button name="count" class="count px-5 py-3 textwhite shadow-lg">Count</button>
</form>
<br> <br>
<form method="post"> {% csrf_token %}
<button name="reset" class="reset px-5 py-3 textwhite shadow-lg">Reset</button>
</form>
</div>
</body>
</html> यहाँ फ़्रंटएंड है जिसे हम होम url पर प्रस्तुत कर रहे हैं।
आउटपुट

गणना . पर क्लिक करना बटन संख्या में 1 जोड़ देगा और रीसेट बटन पर क्लिक करने से रीसेट हो जाएगा काउंटर टू 0.