初めてのテンプレート
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"を探します。そのため、次の2つが正しく設定されている必要があります。- アプリが
INSTALLED_APPSに登録されていること。 - ファイルが
shop/templates/shop/cart.htmlにあること。shopを繰り返すことで、別のアプリのcart.htmlと区別できます。
どちらか一方でも欠けていると、ページはTemplateDoesNotExistでエラーになり、Djangoが検索したすべてのフォルダーが一覧表示されます。home.html内の{% url %}タグは「About」リンクを作成します。詳しくは後のレッスンで説明します。
チャレンジ
簡単ホームページのHTMLはmenu/templates/menu/home.htmlに用意されています。homeビューでそれをレンダリングし、Djangoが見つけられるようにしてください。
Runを押します。サイトのタイトルバーにはCorner Caféと表示されます。黄色いTemplateDoesNotExistページが表示された場合は、検索されたフォルダーを確認してください。
自分で試してみよう
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プレイグラウンド