Menu
CoddyTech

你的第一个模板

本课属于 Coddy Django 学习旅程的“Django 基础”单元。第 11 课,共 23 课。

主页的 HTML 已经太长,不适合放在 Python 字符串中。Django 会将 HTML 保存在模板中,这是一个由视图渲染的文件。商店的购物车视图:

from django.shortcuts import render


def cart(request):
    return render(request, "shop/cart.html")

render()会读取模板,填入内容并返回一个HttpResponse。Django 会在settings.py中INSTALLED_APPS里的每个应用的templates/文件夹中查找"shop/cart.html"。因此,以下两点必须正确:

  • 应用已添加到INSTALLED_APPS中;
  • 文件位于shop/templates/shop/cart.html。重复的shop可以避免它与其他应用的cart.html混淆。

如果其中任何一点不对,页面就会因TemplateDoesNotExist而崩溃,并列出 Django 搜索过的所有文件夹。home.html中的{% url %}标签会生成“关于”链接,后续课程会对此进行讲解。

challenge icon

挑战

简单

首页的 HTML 已准备好,位于 menu/templates/menu/home.html。让 home 视图渲染它。

  1. 在 mysite/settings.py 中,将 "menu" 添加到 INSTALLED_APPS。Django 只会在此处列出的应用中查找模板。
  2. 在 menu/views.py 中,从 django.shortcuts 导入 render,并替换 home 视图中的 return 行,让它渲染 "menu/home.html"。

按下运行:网站的标题栏显示 Corner Café。

亲手试试

from django.http import Http404, HttpResponse
from django.urls import reverse

DRINKS = {
    "espresso": {"name": "Espresso", "price": 2.5, "description": "A short, strong shot of coffee."},
    "latte": {"name": "Latte", "price": 3.5, "description": "Espresso with lots of steamed milk."},
    "flat-white": {"name": "Flat White", "price": 3.75, "description": "Espresso with a thin layer of silky milk."},
    "hot-chocolate": {"name": "Hot Chocolate", "price": 3, "description": "Dark chocolate melted into warm milk."},
}


def home(request):
    about_url = reverse("menu:about")
    return HttpResponse(
        "<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>"
        f'<a href="{about_url}">About us</a>'
    )


def about(request):
    return HttpResponse("Corner Café opened in 2026.")


def hours(request):
    return HttpResponse("Open every day from 8:00 to 18:00.")


def contact(request):
    return HttpResponse("Write to us at hello@cornercafe.example.")


def table(request, number):
    return HttpResponse(f"<h1>Table {number}</h1>")


def drink(request, slug):
    if slug not in DRINKS:
        raise Http404(f"No drink called {slug}")
    item = DRINKS[slug]
    return HttpResponse(f"<h1>{item['name']}</h1><p>{item['description']}</p>")


def order(request):
    size = request.GET.get("size", "medium")
    if size not in ["small", "medium", "large"]:
        size = "medium"
    return HttpResponse(f"You ordered a {size} coffee.")

Django 基础中的所有课

自己练习: Django 在线编辑器