Django Templates: Mastering the Basics

Emmanuel Iyke
9 min readOct 2, 2023

Django templates play an essential role in any Django project, it serves as a medium to connect the user interface with the applications logic. in this article, we will dive into the fundamentals of the Django template, we will learn how to use Django templating to create dynamic and user-friendly web applications.

What are Django templates?

Django templates are the HTML files that define the structure and content of your web application. They act as the visual layer of your application, allowing you to create web pages with dynamic elements. These templates are typically used with Django views and models to build complete web applications.

Setting up a Django template

In order to explore Django templates, we must first set up a project. For testing purposes, our project will involve creating a basic quiz application a straightforward quiz website featuring a single question, four answer options, and a submit button to determine whether the answer is correct or incorrect.

We first need to run our virtual environment to prevent conflict with other projects or system packages. open the terminal from your vs code and input

python3 -m venv qvenv

Now we need to activate it

source qvenv/bin/activate

Next, we install Django on our virtual device

pip install django 

Next, we need to start the project quiz project

django-admin startproject quiz_project

To keep our project organized let's move into the folder before creating the app

cd quiz_project 

django-admin startapp quiz

Template configuration

To configure a Django template i.e. tell Django to recognize the app we just built we need to add the app to our settings.py. In the file quiz_project/settings.py, add the name of the app quiz to the INSTALLED_APPS list:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'quiz'
]

Next, we add this line of code to our quiz_project/url.py, this line of code is important for routing our URL to the app

from django.contrib import admin
from django.urls import path, include #👈 1.include this

urlpatterns = [
path('admin/', admin.site.urls),

# 👇 2. add this line too
path('', include('quiz.url'))
]

Create a URL file: if you notice the URL file we called in the include doesn't exist, to add that create a URL route file urls.py inside quiz the folder. By creating a dedicated quiz.urls module, you keep all the URL patterns for the "quiz" app in one place. This makes it easier to manage and maintain the URLs specific to that app, especially as our project grows and the number of URLs increases

from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='home'),
]

Rendering a Django Template

Now that we have a basic understanding of Django template and how to set it up, let’s take a look at how to render a template in a Django view. In Django, a view is a function that handles an HTTP request and returns an HTTP response.

Let’s create a simple view that renders the template we created earlier:

Open quiz/views.py and add this function.

from django.shortcuts import render

def index(request):
context = {
'question': 'What is the most widely used Python framework?',
'option1': 'Django',
'option2': 'Flask',
'option3': 'Pyramid',
}
return render(request, 'index.html', context)

Basics of Django Templating

As we said earlier Django templating allows us to separate the design (that is the presentation) of the data from the application logic. This means that you can create HTML templates that can be dynamically generated by Django based on the data that is provided.

To be able to achieve this we need to understand certain aspects of Django which include:

Variables:

variables are placeholders that allow you to insert dynamic data into your HTML templates. and they look something like this: {{variable}}, they are used to output the value of contents sent by the view.

Create a templates folder inside the myproject folder and create an index.html file copy content & paste it into index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Framework Quiz</title>
</head>
<body>
<h1>Python Framework Quiz</h1>
<h2>Question:</h2>
<p>{{ question }}</p>

<input type="radio" name="answer" value="{{ option1 }}" id="option1">
<label for="option1">{{ option1 }}</label><br>

<input type="radio" name="answer" value="{{ option2 }}" id="option2">
<label for="option2">{{ option2 }}</label><br>

<input type="radio" name="answer" value="{{ option3 }}" id="option3">
<label for="option3">{{ option3 }}</label><br>

<button type="submit">Check Answer</button>
</body>
</html>

To load a template from disk, you first need to tell Django where to find it. Inside of quiz_project/settings.py, modify the "DIRS" value in TEMPLATES:

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
#👇add this line to your code
BASE_DIR / "templates",
],
"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",
],
},

Now the output would be something like this

As we can see the values we inputted are being passed into the variable.

Tags

Django template tags are essential tools for executing arithmetic operations, logical conditions, and incorporating external data into your Django templates. They are typically enclosed within curly braces and percentage signs, resembling this format: {% tag %}

Django comes equipped with approximately twenty pre-defined template tags. Here are a few of the frequently utilized ones:

  • for — Allows you to iterate through an array, such as looping through story items in the given example to showcase a list of stories from story_list.
  • if, elif, and else — This set of tags is used for assessing a variable. If the variable is determined to be “true,” the contents within the block are shown.

Let's take a look at an example of how the for loop works

Open quiz/views.py and make a few modifications, we are trying to retrieve data from the view, allowing us to iterate through its contents using a loop.

def index(request):
question = 'What is the most widely used Python framework?'
options = ['Django', 'Flask', 'Pyramid']

context = {
'question': question,
'options': options,
}
return render(request, 'index.html', context)

Now, in our index.html template, let's iterate through the data to extract the required values from it.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Framework Quiz</title>
</head>
<body>
<h1>Python Framework Quiz</h1>
<h2>Question:</h2>
<p>{{ question }}</p>

{% for option in options %}
<input type="radio" name="answer" value="{{ option }}" id="{{ option }}">
<label for="{{ option }}">{{ option }}</label><br>
{% endfor %}

<button type="submit">Check Answer</button>

</body>
</html>

As we can see the for loop allows us to extract data from the variables.

Filters

Filters are special tools used within template tags to modify or format data displayed in templates. Filters are applied to variables using the pipe (|) symbol, such as {{ variable|filter_name }}. They allow you to transform data in various ways, such as converting text to lowercase, formatting dates, or filtering queries. The most commonly used filters include :

lower — Example: {{ name|lower }} — This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase. Use a pipe (|) to apply a filter.

truncatewords — Some filters take arguments. A filter argument looks like this: {{ bio|truncatewords:30 }}. This will display the first 30 words of the bio variable.

default — If a variable is false or empty, use the given default. Otherwise, use the value of the variable.

For example: {{ value|default:”nothing” }}

If the value isn’t provided or is empty, the above will display “nothing”.

Template Inheritance

The most powerful and the most complex part of Django’s template engine is template inheritance. Template inheritance allows us to build a base “skeleton” template that contains all the common elements of your site so our other templates can inherit its properties. This helps you maintain a consistent layout and structure across multiple pages of your website while customizing the content for each page.

Let’s illustrate template inheritance using our index.html code as an example:

Now let's create a new HTML file called base.html this serves as the base template, defining the overall structure of our website. It will contain placeholders enclosed within {% block %} tags for the title and content

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<header>
<h1>Python Fraework Quiz</h1>
</header>

<main>
{% block content %}{% endblock %}
</main>

<footer>
&copy; 2023 My Website
</footer>
</body>
</html>

Now for our index.html we will modify the code to have something like this:

{% extends "base.html" %}
{% block content %}
<h2>Question:</h2>
<p>{{ question }}</p>

{% for option in options %}
<input type="radio" name="answer" value="{{ option }}" id="{{ option }}">
<label for="{{ option }}">{{ option }}</label><br>
{% endfor %}

<button type="submit">Check Answer</button>

{% endblock %}

{% extends "base.html" %}: This line indicates that the index.html template extends the base.html template. This establishes a relationship where index.html inherits the structure and layout defined in base.html. This means that the content of index.html will be placed within the {% block content %} block of the base.html template.

Results :

To view the result we need to connect one view to another, to do that in Django, you first create a new view in our quiz/views.py file. This view will contain the data or answer you want to pass to the second view.

def form_view(request):
if request.method == "POST":
result = request.POST.get("answer")
context = {"result": result }
return render(request, "result.html", context)

In this example, we have a view form_view that handles a form submission. When the form is submitted, the view captures the user's answer from the POST data and stores it. it then renders into a HTML template named result.html and passes the captured answer data.

Let's create the result.html so we can get our results (data)

{% extends "base.html" %}
{% block title %}Result Page{% endblock %}
{% block content %}
Right answer <b>Django</b>
<p>Your Answer : {{ result }}
{% endblock content %}

As we can see, this result.html extends our base html file which contains our title and content. It gets our result from our post URL and displays it in the HTML template

To create our URL we need to add and update the code in our quiz/url.py

from django.urls import path
from . import views
from .views import form_view, index


urlpatterns = [ path('', views.index, name='home'),
#👇add this line to your code
path("result", form_view, name="form_view"),
]

The URL path allows us to access our result.htmlby going to the /result URL.

Now before we run the code let's update our index.htmlto handle the click event.

{% extends "base.html" %}
{% block content %}
<h2>Question:</h2>
<p>{{ question }}</p>

#👇add this line to your code
<form action="{% url 'form_view' %}" method="post">
{% csrf_token %}
{% for option in options %}
<input type="radio" name="answer" value="{{ option }}" id="{{ option }}">
<label for="{{ option }}">{{ option }}</label><br>
{% endfor %}
<button type="submit">Check Answer</button>

#👇add this 2nd line to your code to close the form
</form>
{% endblock %}

Finally, if we run the codebase and click on a result we will get something like this

Conclusion:

Django template tags and filters give you a powerful way to build HTML output in a reusable fashion. Templates are defined in their own language in order to separate the business logic from the display logic. Tags are like the keywords and functions of the language, while filters allow you to modify existing data before displaying it.

In this tutorial, We learned how to:

  1. Template Compilation: We learned how to utilize the Django Template and Context objects to compile templates, providing a foundation for dynamic content rendering.
  2. Template Management: We discovered how to load templates from files and leverage the render() shortcut to return them in views, streamlining the rendering process.
  3. Conditional and Looping Blocks: We explored the power of conditional blocks ({% if %}) and looping blocks ({% for %}) to dynamically generate content based on data.
  4. Template Inheritance: By using extends and include, we uncovered the benefits of creating reusable template components, allowing for consistent layouts and modular development.
  5. Connecting views with URL

If you have any questions, feel free to reach out to me at Linkedin.

To have access to the source code click here

--

--