文章

Python 首批细教程 · 04A:用 Django 做一个能 Ajax 投票的小页面

#271 · 2026-05-13 · Python 教程拆解

对应原仓库41.Django快速上手.md43.静态资源和Ajax请求.md

已提供完整示例工程/tutorial-assets/python-100-days/04a-django-ajax-vote/(站点源码路径:blog-src/static/tutorial-assets/python-100-days/04a-django-ajax-vote/

很多人学 Django 只会 runserver,但不知道“页面点击一下,后端怎么把计数加 1,再把 JSON 回给前端”。

这一篇就练这件事。

Step 1:起项目

cd blog-src/static/tutorial-assets/python-100-days/04a-django-ajax-vote
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Step 2:写最小视图

voteproj/urls.py 里:

from django.contrib import admin
from django.urls import path
from vote import views

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", views.index),
    path("praise/", views.praise),
]

vote/views.py 里:

from django.http import JsonResponse
from django.shortcuts import render

counter = {"good": 0}


def index(request):
    return render(request, "index.html", {"count": counter["good"]})


def praise(request):
    counter["good"] += 1
    return JsonResponse({"code": 20000, "count": counter["good"]})

Step 3:写模板

建目录 vote/templates/index.html

<!doctype html>
<html lang="zh-CN">
<body>
  <h1>最小投票页</h1>
  <button id="btn">好评</button>
  <strong id="count">{{ count }}</strong>

  <script>
    document.getElementById("btn").addEventListener("click", async () => {
      const resp = await fetch("/praise/");
      const json = await resp.json();
      document.getElementById("count").textContent = json.count;
    });
  </script>
</body>
</html>

Step 4:运行

python manage.py runserver

访问首页,点击按钮,数字会递增。

你在练什么

这一步几乎就是原仓库 43.静态资源和Ajax请求.md 的最小闭环版:

  • URL 映射;
  • 视图函数;
  • JsonResponse
  • 前端 fetch / Ajax;
  • 页面局部更新。

进阶任务

  1. 再加一个 /criticize/ 路由。
  2. 把内存计数器换成数据库模型。
  3. 给按钮增加禁用态和错误提示。

常见坑

  • 忘记把 templates 放在 Django 能找到的位置。
  • 前端不 await resp.json() 就直接用数据。
  • 把 GET/POST、页面请求/Ajax 请求混成一坨。