Menu
CoddyTech

Your First Template

Part of the Django Basics section of Coddy's Django journey. Lesson 11 of 23.

The home page's HTML has grown too long for a Python string. Django keeps HTML in a template, a file the view renders. A shop's cart view:

from django.shortcuts import render


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

render() reads the template, fills it in and returns an HttpResponse. Django looks for "shop/cart.html" in the templates/ folder of every app in INSTALLED_APPS, in settings.py. So two things must be right:

  • the app is in INSTALLED_APPS;
  • the file is at shop/templates/shop/cart.html. The repeated shop keeps it apart from another app's cart.html.

Miss either and the page crashes with TemplateDoesNotExist, listing every folder Django searched. The {% url %} tag in home.html builds the About link; a later lesson explains it.

challenge icon

Challenge

Easy

The home page's HTML is ready in menu/templates/menu/home.html. Make the home view render it.

  1. In mysite/settings.py, add "menu" to INSTALLED_APPS. Django finds templates only in apps listed there.
  2. In menu/views.py, import render from django.shortcuts and replace the home view's return line so it renders "menu/home.html".

Press Run: the site's title bar reads Corner Café.

Try it yourself

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.")

All lessons in Django Basics

Practice on your own: Django playground