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

אתגר

קל

גרום לתצוגת drink להעלות Http404 כאשר ה-slug לא נמצא ב-DRINKS. /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 אונליין