Django, a powerful Python-based web framework, is known for its simplicity and flexibility in building web applications. One of its most useful features is the template system. This guide will take you through everything you need to know about Django templates, whether you’re a beginner or looking to brush up on your skills.
What Is A Django Template
A Django template is an HTML file mixed with Django Template Language (DTL). It’s designed to separate the presentation logic (what the user sees) from the backend logic (how the data is processed). In simple terms, templates allow you to dynamically generate HTML based on the data you want to show to your users.
Setting Up Django Templates
To get started with Django templates, you need to configure your Django project. Here’s how:
If you want to learn how to create a Django project, click here:
Step 1: Create A templates
Directory
Create a templates
folder in the root of your Django project. This folder will hold all your HTML files.
bashmkdir templates
Step 2: Update Your settings.py
In your settings.py
file, add the templates
directory to the DIRS
option within the TEMPLATES
setting.
python# settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], # Add your templates 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', ], }, }, ]
Step 3: Create a Simple Template
Inside the templates
folder, create an HTML file, e.g., index.html
.
html<!-- templates/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome to My Django Site</title> </head> <body> <h1>Hello, {{ name }}!</h1> </body> </html>
This template displays the value of the variable name
using Django’s double curly braces {{ }}
syntax.
Rendering Templates In Django Views
Now that your template is set up, you need to render it in a Django view. In Django, views are Python functions or classes that handle logic and return HTTP responses.
Step 4: Create a View
In your views.py
, create a view that renders the index.html
template:
python# views.py from django.shortcuts import render def home(request): context = {'name': 'Andrew'} return render(request, 'index.html', context)
Here, render()
is a built-in function that takes three arguments:
request
: The HTTP request object.'index.html'
: The template name.context
: A dictionary with values to be rendered in the template.
Step 5: Create A URL Pattern
To make the view accessible via a URL, update your urls.py
:
python# urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]
Now when you visit the root URL of your project, Django will render the index.html
template with the context provided in the view.
Template Inheritance
One of the most powerful features of Django templates is inheritance. You can define a base template that includes common elements like headers, footers, or navigation bars, and then extend this base template in other pages.
Step 6: Create a Base Template
html<!-- templates/base.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}My Django Site{% endblock %}</title> </head> <body> <header> <h1>My Site Header</h1> </header> <div class="content"> {% block content %} <!-- Page-specific content will be here --> {% endblock %} </div> <footer> <p>© 2024 My Django Site</p> </footer> </body> </html>
The {% block %}
tag allows you to define sections that child templates can override.
Step 7: Extend The Base Template
Now, create another template that extends base.html
:
html<!-- templates/about.html --> {% extends 'base.html' %} {% block title %} About Us {% endblock %} {% block content %} <h2>About Our Website</h2> <p>This is a sample page built using Django templates.</p> {% endblock %}
With the {% extends %}
tag, about.html
will inherit the structure from base.html
while replacing the title and content blocks.
Step 8: Update the View
Create a view to render this new template:
python# views.py def about(request): return render(request, 'about.html')
And update your urls.py
to include a path for the about page:
python# urls.py urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), ]
Now, when you visit /about/
, Django will render about.html
, extending the base.html
template.
Template Tags and Filters
Django provides various template tags and filters that allow you to add logic to your templates.
Common Template Tags
- {% for %}: Loop through a list.
html<ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul>
- {% if %}: Conditional rendering.
html{% if user.is_authenticated %} <p>Welcome back, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %}
Template Filters
Filters allow you to modify values. For example:
html<p>{{ name|upper }}</p> <!-- Converts name to uppercase -->
Django has many built-in filters like date
, length
, and default
. You can even create custom template filters.
Static Files In Templates
Django templates also handle static files (CSS, JavaScript, images). Static files need to be included in your templates using the {% static %}
tag.
Step 9: Add Static Files
To use static files, follow these steps:
- Create a
static
directory in the root of your app. - In your HTML template, load static files like this:
html{% load static %} <link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}">
This will load the styles.css
file from the static
directory.
Conclusion
Django templates are a powerful way to separate business logic from presentation, allowing you to build flexible, dynamic web pages. By mastering templates, you can streamline your development process and keep your code clean and maintainable.
Key Takeaways:
- Use Django templates to create dynamic HTML pages.
- Template inheritance lets you reuse common layouts.
- Django template tags and filters offer flexibility in rendering logic.
- Always configure static files for CSS, JavaScript, and images in your templates.
With Django templates, you’re well on your way to building fully functional web applications that are not only clean but also scalable.