Template Inheritance allows multiple pages to share a common layout.
Instead of repeating the same HTML code on every page, we create one base template and reuse it.
Suppose we have Home, About and Contact pages. Each page contains the same Header, Navigation Menu and Footer.
If we update the menu, we must modify every page individually.
Create a common template and let other pages inherit from it.
We will create a common layout file named base.html.
demo/templates/base.html
<html>
<head>
<title>My Website</title>
</head>
<body>
<header>
<h1>My Django Website</h1>
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/contact/">Contact</a>
</header>
<hr>
{% block content %}
{% endblock %}
<hr>
<footer>
Copyright © 2026
</footer>
</body>
</html>
{% extends 'base.html' %}
{% block content %}
<h2>Home Page</h2>
<p>Welcome to Django.</p>
{% endblock %}
{% extends 'base.html' %}
{% block content %}
<h2>About Page</h2>
<p>About Us.</p>
{% endblock %}
The tags {% block content %} and {% endblock %} act like a placeholder area in the base template.
Any HTML code written between these tags will be inserted into the content section of base.html.
{% block content %}
<h2>Home Page</h2>
<p>Welcome to Django.</p>
{% endblock %}
Think of it as a start tag and end tag that define the page-specific content area.
Static files are files that do not change, such as CSS, JavaScript and Images.
Django provides a special folder structure to manage static files.
demo
│
├── templates
│ ├── base.html
│ ├── home.html
│
├── static
│ ├── css
│ │ └── style.css
│ │
│ ├── js
│ │ └── script.js
│ │
│ └── images
│
└── views.py
demo/static/css/style.css
body{
background-color:#f8f9fa;
}
h1{
color:blue;
}
Add the following line at the top of base.html
{% load static %}
<link rel="stylesheet"
href="{% static 'css/style.css' %}">
{% load static %}
and
{% static 'path' %}
to access CSS, JavaScript and Images.
Bootstrap helps us create responsive and professional websites quickly.
We will add Bootstrap in base.html so all pages can use Bootstrap classes.
demo/templates/base.html
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet">
</head>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
{% extends 'base.html' %}
{% block content %}
<div class="container mt-5">
<h1 class="text-primary">
Welcome To Django
</h1>
<button class="btn btn-success">
Learn More
</button>
</div>
{% endblock %}
Django allows us to send data from a View to an HTML page.
This data can then be displayed inside the template.
from django.shortcuts import render
def home(request):
data = {
'name':'Shree'
}
return render(request,'home.html',data)
{% extends 'base.html' %}
{% block content %}
<h2>Welcome {{ name }}</h2>
{% endblock %}
{{ name }}
with the value received from the View and displays:
Welcome Shree
{
'name':'Shree',
'city':'Pune',
'course':'Python Django'
}