Templates: Making It Look Good π¨
8 min read
In the early days of web development, developers used to write raw HTML directly inside their backend code, returning massive, messy strings of text. If you write HTML directly inside your Python strings today, a developer from 1997 will haunt your codebase.
Mixing logic (Python) and presentation (HTML) makes code incredibly difficult to read, maintain, and scale.
The Solution: Django Templates.
Django separates the logic from the presentation. You write your Python code in Views, and you write your HTML in Templates. Django then merges the two before sending the final web page to the user.
Let's break down how to make your Django apps look good and function beautifully, starting from the absolute basics.
1. Django Template Language (DTL): Variables & Tags
Definition
The Django Template Language (DTL) is a built-in templating engine that allows you to embed Python-like syntax into HTML files. It evaluates this syntax to generate dynamic HTML documents.
The Problem
Standard HTML is entirely static. If you write <h1>Hello, User!</h1>, it will always say "User". If you want to display the actual name of the logged-in user, or loop through a list of products from a database, standard HTML cannot do it.
The Solution: Variables, Tags, and Filters
DTL solves this by introducing three main syntaxes into your HTML:
- Variables
{{ }}: Used to output data. Think of it as "print this value here." - Tags
{% %}: Used for logic. Think of it as "do something here" (like loops or if-statements). - Filters
|: Used to modify variables before they are displayed.
Variables
If your backend sends a variable called username, you display it like this:
<h1>Welcome back, {{ username }}!</h1>Under the hood: Django parses the HTML file, spots the {{ username }} marker, and replaces it with the actual string value from Python before sending it to the browser.
Tags (Logic)
In industry practice, you will almost exclusively use if statements and for loops.
The if statement:
{% if is_logged_in %}
<p>Welcome to your dashboard!</p>
{% else %}
<p>Please log in to continue.</p>
{% endif %}The for loop:
<ul>
{% for item in shopping_cart %}
<li>{{ item.name }} - ${{ item.price }}</li>
{% endfor %}
</ul>Filters
Filters tweak the data right before it hits the page. A common industry problem is handling missing data or formatting dates.
<!-- If bio is empty, show the default text instead -->
<p>{{ user.bio|default:"This user prefers to keep an air of mystery." }}</p>
<!-- Format a raw database date into "February 25, 2026" -->
<p>Joined on: {{ user.date_joined|date:"F j, Y" }}</p>2. Template Inheritance: Don't Repeat Yourself (DRY)
Definition
Template inheritance is a structural mechanism that allows you to create a base "skeleton" HTML template containing common site elements, and then create child templates that override specific blocks of that skeleton.
The Problem
Every web page on your site usually shares the same navigation bar, footer, and <head> metadata. Copy-pasting this HTML into 50 different files is a maintenance nightmare. If the marketing team asks you to change the footer link, you would have to edit 50 files manually. You will probably miss one, and your boss will notice.
The Solution: {% extends %} and {% block %}
Imagine you are building a fleet of cars (the system simulation). Every car needs a chassis, four wheels, and an engine. This is your base template. The specific paint job, leather seats, and radio are the child templates. You don't rebuild the engine every time you want a red car; you just add the red paint to the base chassis.
Step 1: Create the Base Skeleton (base.html)
Define the common structure and punch "holes" in it using {% block %}. These holes are where the child templates will inject their specific content.
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Awesome Site{% endblock %}</title>
</head>
<body>
<nav>
<ul><li>Home</li><li>About</li></ul>
</nav>
<main>
<!-- This is a hole punched in the template for child content -->
{% block content %}
{% endblock %}
</main>
<footer>Copyright 2026</footer>
</body>
</html>Step 2: Create the Child Template (home.html)
The child template declares that it inherits from the base, and then it fills in the blocks.
<!-- home.html -->
{% extends "base.html" %}
{% block title %}Home | My Awesome Site{% endblock %}
{% block content %}
<h1>Welcome to the Homepage</h1>
<p>This paragraph will be injected right into the main tag of base.html!</p>
{% endblock %}Industry Standard: Always use a base.html. In larger apps, you might even have multiple layers (e.g., base.html -> dashboard_base.html -> user_profile.html).
3. Passing Context: Sending Data from View to Template
Definition
Context is a Python dictionary that maps variable names (strings) to Python objects. It is the transport mechanism used to send data from a View to a Template.
The Problem
The template knows exactly how to format and display data (thanks to DTL), but it has no idea what the data actually is. The View fetches the data from the database, but it doesn't know how to make it look pretty. They need a way to communicate.
The Solution: The render() function
Imagine a restaurant kitchen. The View is the chef who cooks the food (gets data from the database). The Template is the plating station that makes it look good. The Context is the waiter's tray carrying the food from the chef to the plating station.
Here is how you pass data from a Python view to an HTML template:
# views.py
from django.shortcuts import render
from .models import Product
def product_list(request):
# 1. Fetch data from the database
products = Product.objects.all()
user_role = "Admin"
# 2. Pack the data into a dictionary (The Context)
context = {
'inventory': products,
'role': user_role,
}
# 3. Render the template, passing the request, template name, and context
return render(request, 'products/list.html', context)Now, inside list.html, you can use {{ role }} and loop over inventory using {% for item in inventory %}.
Under the hood: The render() function takes your request, reads the list.html file into memory, injects the context dictionary values into the DTL variables/tags, compiles it all into a single giant HTML string, and returns it as an HttpResponse to the user's browser.
4. Serving Static Files: Integrating CSS, JS, and Images
Definition
Static files are assets that do not change dynamically per user request. This includes CSS stylesheets, JavaScript files, and images (like logos).
The Problem
In standard HTML, you link a CSS file like this: <link rel="stylesheet" href="/style.css">.
However, Django acts as a gatekeeper. It routes URLs to Python views. If a browser asks Django for /style.css, Django will look at its URL routes, realize there is no view named style.css, and return a 404 Not Found error. Your site will load, but it will look like a barebones Wikipedia page from 2001.
The Solution: The Static Files App
Django has a built-in app specifically designed to bypass the view-routing system and serve files directly.
Step 1: Configure Settings (Latest Boilerplate)
Open your settings.py. Ensure django.contrib.staticfiles is in your INSTALLED_APPS (it is by default). Then define where Django should look for these files.
# settings.py
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
# The URL prefix for static files (how it looks in the browser)
STATIC_URL = 'static/'
# Where your actual folders are located on your hard drive
STATICFILES_DIRS = [
BASE_DIR / "static",
]Step 2: Organize Your Files
Create a folder named static in your root directory (next to manage.py). Inside it, put your style.css.
your_project/
βββ manage.py
βββ core_app/
βββ static/
βββ css/
βββ style.cssStep 3: Load Static in Templates
To use these files in your HTML, you must explicitly tell the template engine to load the static file handler, and then use the {% static %} tag to generate the correct URL.
<!-- base.html -->
{% load static %} <!-- MUST be at the top of the file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Styled Site</title>
<!-- Django will dynamically generate the correct path to style.css -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<img src="{% static 'images/logo.png' %}" alt="Company Logo">
</body>
</html>π¨ Industry Production Standard: collectstatic
In a local development environment (when DEBUG = True), Django serves static files automatically. However, in production (when DEBUG = False), Django refuses to serve static files because it is too slow.
In the real world, you use a dedicated server (like Nginx) or a cloud service (like AWS S3) to serve static files. To prepare for this, Django provides a command:
python manage.py collectstaticWhat it does: It scours your entire project, grabs every single static file from every app, and copies them into a single master directory (defined by STATIC_ROOT in settings). The production server then points directly to this master directory to serve files at lightning speed. Forgetting to run this command is the #1 reason beginners cry over broken CSS when deploying their first app.
π References & Extra Reading
Challenge
Challenge: Create a User Profile Page using Django Templates
You are tasked with building a user profile page for a web application. This involves creating a reusable base template and a specific profile template that inherits from it. The profile page must dynamically display user information passed from a view, handle missing data gracefully, and correctly load static assets.
Below is the context dictionary that the view provides to the template. Use this data to populate your templates.
Context Data:
{
'user': {
'username': 'jdoe',
'email': '[email protected]',
'bio': '',
'join_date': a datetime object for January 15, 2024,
'is_active': True,
'projects': [
{'name': 'Project Alpha'},
{'name': 'Project Beta'}
]
}
}Requirements:
1. base.html Template:
- Create a standard HTML5 boilerplate.
- Load Django's static template tags.
- In the
<head>, link to a stylesheet located atcss/profile.cssusing the appropriate DTL tag. - Define a template block named
titleinside the<title>element. - Define a template block named
contentinside the<body>element.
2. profile.html Template:
- This template must inherit from
base.html. - Override the
titleblock to display the page title in the format:Profile: <username>. - Override the
contentblock to display the user's details:- Display the user's
usernamein an<h1>tag and theiremailin a<p>tag. - Display the user's
bio. If the bio is empty, it must display the fallback text "User has not provided a bio." - Display the user's
join_date, formatted asMonth day, Year(e.g.,January 15, 2024). - Use a conditional tag to show the text "Account Status: Active" only if
user.is_activeisTrue. - Loop through the
user.projectslist and display each project's name in an<li>element within a<ul>. If theprojectslist were empty, the template should instead render a single<p>tag with the text "No projects listed."
- Display the user's
Expected result
The solution should consist of two distinct Django templates, base.html and profile.html, written one after the other in the editor.
base.html
- Begins with the
{% load static %}tag. - The
<head>section contains<link rel="stylesheet" href="{% static 'css/profile.css' %}">. - The
<title>tag contains{% block title %}{% endblock %}. - The
<body>tag contains{% block content %}{% endblock %}.
profile.html
- The first line is
{% extends 'base.html' %}. - It defines a
{% block title %}that rendersProfile: {{ user.username }}. - It defines a
{% block content %}which contains the main logic:- Uses
{{ user.username }}and{{ user.email }}to display user info. - Uses the
defaultfilter for the bio:{{ user.bio|default:"User has not provided a bio." }}. - Uses the
datefilter for the join date:{{ user.join_date|date:"F d, Y" }}. - Contains a conditional block:
{% if user.is_active %}Account Status: Active{% endif %}. - Includes a
forloop to iterate overuser.projects:{% for project in user.projects %}. - Inside the loop, it renders
<li>{{ project.name }}</li>. - The
forloop must include an{% empty %}clause that renders<p>No projects listed.</p>.
- Uses