Menu
CoddyTech

Mẫu đầu tiên của bạn

Thuộc phần Kiến thức cơ bản về Django trong hành trình Django của Coddy. Bài học 11 trên 23.

HTML của trang chủ đã trở nên quá dài để chứa trong một chuỗi Python. Django lưu HTML trong một mẫu, tức là tệp mà khung nhìn kết xuất. Khung nhìn giỏ hàng của một cửa hàng:

from django.shortcuts import render


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

render() đọc mẫu, điền nội dung vào rồi trả về một HttpResponse. Django tìm "shop/cart.html" trong thư mục templates/ của từng ứng dụng trong INSTALLED_APPS, nằm trong settings.py. Vì vậy, hai điều sau phải chính xác:

  • ứng dụng nằm trong INSTALLED_APPS;
  • tệp nằm ở shop/templates/shop/cart.html. Tên shop được lặp lại để tránh nhầm lẫn với cart.html của ứng dụng khác.

Nếu thiếu một trong hai điều này, trang sẽ gặp lỗi TemplateDoesNotExist và liệt kê mọi thư mục Django đã tìm kiếm. Thẻ {% url %} trong home.html tạo liên kết About; một bài học sau sẽ giải thích thẻ này.

challenge icon

Thử thách

Dễ

Mã HTML của trang chủ đã sẵn sàng trong menu/templates/menu/home.html. Hãy để view home hiển thị trang này.

  1. Trong mysite/settings.py, thêm "menu" vào INSTALLED_APPS. Django chỉ tìm template trong các ứng dụng được liệt kê ở đó.
  2. Trong menu/views.py, nhập render từ django.shortcuts rồi thay dòng return trong view home để hiển thị "menu/home.html".

Nhấn Chạy: thanh tiêu đề của trang web hiển thị Corner Café.

Tự làm thử

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.")

Tất cả bài học trong Kiến thức cơ bản về Django

Tự luyện tập: Playground Django