इस लेख में, हम देखेंगे कि एक सुपर सिंपल काउंटर ऐप कैसे बनाया जाए, जहां बटन क्लिक करने पर एक नंबर जुड़ जाएगा और यह तब भी करता रहेगा जब आप टैब बंद कर दें और डेटा को सेशन में रखें। हमें सेशन का उपयोग करके एक साधारण ऐप बनाने का आइडिया मिलेगा और सेशन का उपयोग करके डेटा ट्रांसफर कैसे करें।
उदाहरण
urls.py में, निम्नलिखित लाइनें जोड़ें:
from django.urls import path
from django.urls.resolvers import URLPattern
from .import views
urlpatterns = [
path('', views.counterView, name='counter'),
]
यहां हमने होम url पर व्यूज सेट किए।
views.py में, निम्नलिखित लाइनें जोड़ें:
from django.shortcuts import render
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 रिक्वेस्ट हैंडलर बनाया, हम फ्रंटएंड से एक नंबर भेजेंगे और इसे सेशन के 'count' वेरिएबल में सेव करेंगे। जब फ्रंटएंड से reset भेजा जाता है, तो सेशन count 0 हो जाता है।
अब ऐप डायरेक्टरी में एक templates फोल्डर बनाएं और इसमें एक 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=device-width, 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="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" 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="margin-top: 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 text-white shadow-lg">Count</button>
</form>
<br><br>
<form method="post">{% csrf_token %}
<button name="reset" class="reset px-5 py-3 text-white shadow-lg">Reset</button>
</form>
</div>
</body>
</html>
यह फ्रंटएंड है जिसे हम होम url पर रेंडर कर रहे हैं।
आउटपुट

Count बटन क्लिक करने पर नंबर में 1 जुड़ जाएगा और Reset बटन क्लिक करने पर काउंटर reset होकर 0 हो जाएगा।