Menu
CoddyTech

قالبك الأول

جزء من قسم أساسيات Django في رحلة Django على Coddy. الدرس 11 من 23.

أصبح HTML الصفحة الرئيسية طويلًا جدًا بحيث لا يتسع في سلسلة نصية بلغة Python. يحتفظ Django بـ HTML في قالب، وهو ملف يعرضه العرض. إليك طريقة عرض سلة التسوق في متجر:

from django.shortcuts import render


def cart(request):
    return render(request, "shop/cart.html")

تقرأ render() القالب، وتملؤه، ثم تعيد HttpResponse. يبحث Django عن "shop/cart.html" في المجلد templates/ لكل تطبيق مدرج في INSTALLED_APPS ضمن settings.py. لذا يجب التأكد من أمرين:

  • أن التطبيق مُدرج في INSTALLED_APPS؛
  • أن الملف موجود في shop/templates/shop/cart.html. يمنع تكرار shop اختلاطه بملف cart.html لتطبيق آخر.

إذا أخطأت في أيٍّ منهما، فسيتعطل تحميل الصفحة مع ظهور TemplateDoesNotExist، الذي يسرد كل المجلدات التي بحث فيها Django. ينشئ الوسم {% url %} في home.html رابط «حول»؛ وسيشرح درس لاحق هذا الوسم.

challenge icon

التحدي

سهل

ملف HTML للصفحة الرئيسية جاهز في menu/templates/menu/home.html. اجعل العرض home يعرضه.

  1. في mysite/settings.py، أضف "menu" إلى INSTALLED_APPS. لا يعثر Django على القوالب إلا في التطبيقات المدرجة هناك.
  2. في menu/views.py، استورد render من django.shortcuts واستبدل سطر return في العرض home ليعرض "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

تدرّب بنفسك: Playground لـ Django