Menu
CoddyTech

Http404を発生させる

CoddyのDjangoジャーニー「Djangoの基礎」セクションの一部。レッスン 9/23。

/drinks/mocha/を開きます。ルートには一致しますが、DRINKS["mocha"]でKeyErrorが発生し、サイトはサーバーエラーを示すステータス500で応答します。訪問者には、サイトが壊れているように見えます。

正しい応答は404、つまりそのようなページは存在しないというものです。ビューはHttp404を発生させることで、そのことを示します。カフェにはテーブルが12台あるので、tableビューは/table/40/を拒否できます。

from django.http import Http404, HttpResponse


def table(request, number):
    if number > 12:
        raise Http404(f"There is no table {number}")
    ...
raiseであり、returnではありません。Http404は例外で、Djangoはこれを通常の404ページに変換します。HttpResponse("No such page")を返すと、ステータス200でその文言が表示され、ブラウザーや検索エンジンにはそのページが存在すると伝わります。
challenge icon

チャレンジ

簡単

slug が DRINKS に含まれていない場合、drink ビューで Http404 を発生させます。/drinks/latte/ は引き続き動作します。

Run を押します。プレビューで /drinks/mocha/ が開き、メッセージが表示された 404 ページが表示されます。

自分で試してみよう

from django.http import HttpResponse

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):
    return HttpResponse("<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>")


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):
    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プレイグラウンド