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 repeatedshopkeeps it apart from another app'scart.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
EasyThe home page's HTML is ready in menu/templates/menu/home.html. Make the home view render it, and make sure Django can find it.
Press Run: the site's title bar reads Corner Café. If the yellow TemplateDoesNotExist page shows, read the folders it searched.
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
3Templates
Your First TemplateTemplate VariablesPractice on your own: Django playground