使用 Django 中的 request.session 構建一個簡單的計數器應用


在本文中,我們將瞭解如何製作一個超簡單的計數器應用,單擊一個按鈕將新增一個數字,即使關閉選項卡,它仍會執行該操作並將資料儲存在對話中。我們將瞭解如何使用對話來製作一個簡單的應用以及如何使用對話傳輸資料

示例

urls.py 中,新增以下幾行 −

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

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

我們在此設定了 home url 上的檢視。

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 請求處理程式,我們將在前端傳送一個數字,並將其儲存在對話的 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=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" 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>

這裡是在 home url 上呈現的前端。

輸出

單擊 計數 按鈕將在數字中新增 1,單擊重置按鈕將計數器 重置 為 0。

更新於: 2021-08-26

623 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告