← All tutorials

Templates / 7 MIN READ

Build a page with Django templates

Keep Python and HTML easy to read with a base template, a child template, and context data.

01 Create your template directory

Continue with the core app from the getting-started tutorials. The default APP_DIRS setting allows Django to discover templates inside installed apps. The extra core directory keeps template names distinct.

Code example
mkdir -p core/templates/core

02 Add a base template

Save this as core/templates/core/base.html. Blocks give child templates a place to supply their own content while sharing the page structure.

Code example
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{% block title %}My notes{% endblock %}</title>
</head>
<body>
  <nav><a href="{% url 'home' %}">Home</a></nav>
  <main>{% block content %}{% endblock %}</main>
</body>
</html>

03 Add a child template

Create core/templates/core/home.html. Django escapes template variables by default, which helps keep user-provided text from becoming executable HTML.

Code example
{% extends "core/base.html" %}
{% block title %}Welcome{% endblock %}
{% block content %}
  <h1>{{ heading }}</h1>
  <p>A small place for things I learn.</p>
{% endblock %}

04 Render the page

Update core/views.py. Keep the home URL from the previous tutorial, then open the homepage. You should see your heading inside the shared layout.

Code example
from django.shortcuts import render


def home(request):
    return render(request, "core/home.html", {"heading": "My Django notes"})
Keep exploring

Read the official Django documentation for details and more examples.