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ênshopđược lặp lại để tránh nhầm lẫn vớicart.htmlcủ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.
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.
- Trong
mysite/settings.py, thêm"menu"vàoINSTALLED_APPS. Django chỉ tìm template trong các ứng dụng được liệt kê ở đó. - Trong
menu/views.py, nhậprendertừdjango.shortcutsrồi thay dòngreturntrong viewhomeđể 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
1Trang Django đầu tiên của bạn
Xin chào, DjangoTrang thứ hai3Mẫu
Mẫu đầu tiên của bạnBiến trong mẫuTự luyện tập: Playground Django