In the last article, we learned how to handle views and return different types of responses. Now, letβs make those responses beautiful and dynamic using Django Templates and Static Files.
Templates allow you to mix HTML with Python-like logic, and static files (CSS, JS, images) make your pages come alive.
π§© What Are Django Templates?
Django uses the Django Template Language (DTL) to help you embed dynamic content inside HTML.
Example (blog/templates/blog/home.html):
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome, {{ user }}</h1>
<p>{{ message }}</p>
</body>
</html>
You can pass variables from your view:
def home(request):
context = {
'title': 'My Blog',
'user': 'Gopal',
'message': 'Learning Django Templates is fun!'
}
return render(request, 'blog/home.html', context)
Result -> Welcome, Gopal
π§ Template Tags and Filters
You can use logic in templates using special tags.
Example:
{% if user %}
<h2>Hello, {{ user }}!</h2>
{% else %}
<h2>Welcome, Guest!</h2>
{% endif %}
Loops:
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% empty %}
<li>No posts available.</li>
{% endfor %}
</ul>
Filters:
<p>{{ post.content|truncatewords:10 }}</p>
<p>{{ post.published_at|date:"F j, Y" }}</p>
Filters format or modify data inside templates.
π§± Template Inheritance (DRY Principle)
Avoid repeating code like headers and footers using template inheritance.
base.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header><h1>My Blog</h1></header>
<main>
{% block content %}{% endblock %}
</main>
<footer>Β© 2025 My Blog</footer>
</body>
</html>
home.html
{% extends 'blog/base.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h2>Welcome to my blog!</h2>
{% endblock %}
This structure keeps your HTML modular and maintainable.
πΌοΈ Static Files (CSS, JS, Images)
Static files are assets that don't change dynamically.
Folder structure:
blog/
βββ static/
β βββ blog/
β βββ css/
β β βββ style.css
β βββ js/
β β βββ script.js
β βββ images/
β βββ logo.png
settings.py Configuration
STATIC_URL = '/static/'
During development, Django automatically serves static files if DEBUG=True.
Loading Static Files
In your templates:
{% load static %}
<link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
<img src="{% static 'blog/images/logo.png' %}" alt="Logo">
Example style.css
body {
background-color: #fafafa;
font-family: Arial, sans-serif;
margin: 40px;
}
β‘ Best Practices
- Always use load static at the top of the templates.
- Keep static files organized per app (app_name/static/app_name/).
- Use template inheritance for reusable layouts.
- Avoid putting business logic inside templates.
π Summary
Templates render dynamic HTML using context variables.
Template tags and filters add logic and formatting.
Template inheritance keeps layouts DRY.
Static files add design, interactivity, and branding.
Top comments (0)