初めてのテンプレート
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と区別できます。
どちらかを間違えると、Djangoが検索したすべてのフォルダーを一覧表示して、TemplateDoesNotExistエラーでページが停止します。home.html内の{% url %}タグはAboutへのリンクを作成します。後のレッスンで説明します。
チャレンジ
簡単ホームページの HTML は menu/templates/menu/home.html に用意されています。home ビューでそれをレンダリングしましょう。
mysite/settings.pyで、INSTALLED_APPSに"menu"を追加します。Django は、そこに登録されているアプリ内のテンプレートだけを見つけます。menu/views.pyで、django.shortcutsからrenderをインポートし、homeビューのreturn行を置き換えて"menu/home.html"をレンダリングします。
Run を押します。サイトのタイトルバーに 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プレイグラウンド