Welcome to The Coding College, where we simplify web development concepts. In this tutorial, we’ll cover how to prepare templates in Django, a vital skill for building dynamic and user-friendly web applications.
By the end of this guide, you’ll know how to create, configure, and use templates in Django to display dynamic content in your web application.
What is a Template in Django?
A template in Django is an HTML file that defines the structure and layout of your web page. It allows you to embed dynamic content using the Django Template Language (DTL). Templates enable the separation of the user interface from business logic, making your code cleaner and more maintainable.
1. Setting Up the Template Directory
Step 1: Configure the Template Directory
By default, Django looks for templates in the TEMPLATES
setting of your project. Open your project’s settings.py
file and locate the TEMPLATES
configuration:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'], # Specify the template directory here
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DIRS
: Add a path to your customtemplates
folder.APP_DIRS
: When set toTrue
, Django will automatically search for atemplates
folder within each app.
Step 2: Create the Template Folder
- In your project root directory, create a folder named
templates
. - Inside the
templates
folder, create subfolders for organizing templates (e.g.,myapp
,shared
).
2. Creating Your First Template
Step 1: Create an HTML File
In the templates
directory, create a file named index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to The Coding College</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</body>
</html>
Step 2: Use the Template in a View
In your app’s views.py
, create a view to render the template:
from django.shortcuts import render
def home(request):
context = {
'title': 'Django Templates',
'message': 'Learn how to use templates effectively.',
}
return render(request, 'index.html', context)
Step 3: Add a URL Pattern
In your app’s urls.py
, map the view to a URL:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
3. Template Features
Dynamic Content Rendering
Templates allow you to display dynamic content using variables. For example:
<p>Logged in as: {{ user.username }}</p>
Control Structures
Use loops and conditionals for advanced content rendering:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% if user.is_authenticated %}
<p>Welcome back, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
4. Template Inheritance
Template inheritance allows you to define a base template and extend it in other templates.
Base Template (base.html
):
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}The Coding College{% endblock %}</title>
</head>
<body>
<header>{% block header %}Welcome to The Coding College{% endblock %}</header>
<main>{% block content %}{% endblock %}</main>
<footer>{% block footer %}Copyright © 2024{% endblock %}</footer>
</body>
</html>
Extended Template (index.html
):
{% extends 'base.html' %}
{% block title %}Home - The Coding College{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
<p>{{ message }}</p>
{% endblock %}
5. Best Practices for Django Templates
- Organize Templates: Use subdirectories within the
templates
folder to keep templates organized.
templates/
myapp/
index.html
detail.html
shared/
base.html
navbar.html
- Reuse Components: Break your templates into reusable components, like headers, footers, or navigation bars.
- Avoid Business Logic in Templates: Templates should only handle presentation. Perform all logic in views or models.
- Secure Templates: Django automatically escapes variables to prevent XSS attacks. Use
|safe
only when you’re sure the content is safe.
Why Learn Django Templates with The Coding College?
At The Coding College, we provide practical tutorials designed to make your Django development journey smooth and efficient. With a focus on real-world applications, we ensure you gain the skills you need to succeed.
Final Thoughts
Preparing and using templates in Django is a core skill for building dynamic web applications. From rendering dynamic content to reusing layouts through inheritance, Django templates provide the tools you need to create professional-grade websites.
For more coding tutorials and tips, visit The Coding College. Share your thoughts and let us know what you’d like to learn next!