Menu
CoddyTech

העלאת Http404

חלק מהיחידה יסודות Django במסלול ה-Django של Coddy. שיעור 9 מתוך 23.

פתח את /drinks/mocha/. הנתיב תואם, אבל DRINKS["mocha"] מעלה KeyError, והאתר משיב עם קוד מצב 500, שגיאת שרת. למבקר, האתר שלך נראה מקולקל.

התשובה הנכונה היא 404, אין דף כזה. תצוגה מציינת זאת באמצעות העלאת Http404. בבית הקפה יש שתים־עשרה שולחנות, לכן התצוגה 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

אתגר

קל

ב־menu/views.py, גרמו לתצוגת drink להעלות את Http404 כשה־slug אינו נמצא ב־DRINKS.

פתחו את /drinks/mocha/ כדי לראות את הודעת 404, ואז את /drinks/latte/: היא עדיין עובדת.

נסו בעצמכם

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 אונליין