Template Inheritance with base.html
A snippet showing how to use base.html with block tags for template inheritance.
# models.py
from django.db import models
class Page(models.Model):
title = models.CharField(max_length=150)
body = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
# admin.py
from django.contrib import admin
from .models import Page
@admin.register(Page)
class PageAdmin(admin.ModelAdmin):
list_display = ("title", "created_at")
ordering = ("-created_at",)
# Result (Templates)
# base.html defines the layout and blocks; child templates extend and fill blocks.
# templates/base.html
<!doctype html>
<html>
<head>
<title>{% block title %}Site{% endblock %}</title>
{% block head_extra %}{% endblock %}
</head>
<body>
<header>{% block header %}<h1>My Site</h1>{% endblock %}</header>
<main>{% block content %}{% endblock %}</main>
<footer>{% block footer %}© {% now "Y" %}{% endblock %}</footer>
</body>
</html>
# templates/page_detail.html
{% extends "base.html" %}
{% block title %}{{ page.title }} · {{ block.super }}{% endblock %}
{% block content %}
<h2>{{ page.title }}</h2>
<div>{{ page.body }}</div>
{% endblock %}
Explanation:
-
Create a base.html layout with named blocks like
title,content, etc. -
Child templates use
{% extends %}and override blocks as needed. -
Use
{{ block.super }}to append to the parent's block content. - Keeps markup DRY and consistent across pages.
- Category Templates
- Total Views 785
- Last Modified 20 January, 2026
- Tags #templates #inheritance #base #html
Previous snippet
Handle HTMX Requests in Views
Next snippet