Django Templates
A comprehensive introduction to Django Template System for beginners.
This page is a comprehensive introduction to Django Template system, a modern and designer-friendly language for Python used to generate dynamic HTML pages. For newcomers, Django is a high-level Python Web framework that encourages rapid development by reusing modules and libraries built by experienced programmers. On top of this, Django is actively supported by an impressive open-source community - Github stats: 2k contributors, Used by 675k Users, ~58k Stars.
Django Framework - Cover Image.
Before start using Django Template System, we need to install Python, the language used to code Django, and of course, the Django framework.
Install Python
The best way to install Python is to access the download page and use the appropriate installer that matches the operating system. Once the installation process is completed we can check if Python is properly installed directly in the terminal:
1
$ python
2
Python 3.8.4 (tags/v3.8.4:dfa645a, Jul 13 2020, 16:46:45) ...
3
Type "help", "copyright", "credits" or "license" for more information.
4
>>>
Copied!
The next step is to install Django using a virtual environment:
1
$ virtualenv env
2
$ source env/bin/activate
3
$
4
$ pip install django
Copied!
Create a simple Django project
Once Python and Django are installed, we can move forward in developing a Django application by creating a Django project.
1
$ django-admin startproject django_templates
Copied!
This command will automatically create a django_templates folder in the current directory, and all the necessary files for a basic, but fully functioning Django website with an SQLite database. Being a batteries-included framework, Django scaffolds the project with working authentication and administration modules out-of-the-box. To use any of these default features a migration should be executed to create the necessary tables.
1
$ python manage.py migrate
Copied!
Our new Django project can be started using the command:
1
$ python manage.py runserver
Copied!
By default, Django embedded server starts on port 8000.

Django Templates Layer

The default configuration generated can be found in the settings.py file and should look quite similar to this code chunk:
1
TEMPLATES = [
2
{
3
'BACKEND': 'django.template.backends.django.DjangoTemplates',
4
'DIRS': [],
5
'APP_DIRS': True,
6
'OPTIONS': {
7
'context_processors': [
8
'django.template.context_processors.debug',
9
'django.template.context_processors.request',
10
'django.contrib.auth.context_processors.auth',
11
'django.contrib.messages.context_processors.messages',
12
],
13
},
14
},
15
]
Copied!
To enhance this default configuration with a template folder, we need to create the directory somewhere inside the project and update the configuration to inform Django about it.
For simplicity, thetemplates folder will be created in the root of the project
1
$ mkdir templates
Copied!
Updated configuration
1
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates") # <-- new
2
​
3
TEMPLATES = [
4
{
5
'BACKEND': 'django.template.backends.django.DjangoTemplates',
6
'DIRS': [TEMPLATES_DIR], # <-- new
7
'APP_DIRS': True,
8
'OPTIONS': {
9
'context_processors': [
10
'django.template.context_processors.debug',
11
'django.template.context_processors.request',
12
'django.contrib.auth.context_processors.auth',
13
'django.contrib.messages.context_processors.messages',
14
],
15
},
16
},
17
]
Copied!
From this point, we should be able to load the files defined in the templates directory.

Django Templates Language

Once the basic configuration is done, we can move forward and see how this template language can help us to build faster web projects. Here is a short list with features offered by the Django template system:
    Inject variables, Lists, classes into templates
    Filters to transform the information directly in the template in many ways
    Conditionals (test variable presence or value) {% if %}...{% endif %}
    Loops (iterate on lists) - {% for x in y %}...{% endfor %}
    Imports (components reuse) {% include "header.html" %}
    Inheritance (extend page templates) {% extends "base.html" %}
    Block Declaration {% block content %}...{% endblock %}
Let's iterate on each feature and check out the sample code:
Variables and lists
Django template system knows how to render simple variables, class attributes, and even accessing the items of a list by index.
1
{{ my_data }} <-- simple variable
2
{{ address.street }} <-- address is a class
3
{{ my_list.1 }} <-- access list items by index
Copied!
Filters - simple helpers useful to transform the information directly in the template
Here is a short-list with popular helpers: upper, default value, string truncation
1
{{ name|upper }} <-- Uppercase the name
2
{{ discount|default:"0" }} <-- If discount is not provided, value 0 is used
3
{{ title|truncatechars:25 }} <-- Truncate the variable to the desired lenght
Copied!
Another useful feature might be to use more than one filter over a variable:
1
{{ name|lower|capfirst }} <-- name is lowecased
2
<-- Capitalize first letter
Copied!
Comments in Django templates
Django template system will ignore everything between {% comment %} and {% endcomment %}
1
{% comment %}
2
​
3
Here can be a long story <-- Ignored by Django
4
​
5
{% endcomment %}
Copied!
Conditionals - useful to test a variable presence or value
1
{% if discount %}
2
​
3
<span>Special Price {{ discount }}
4
​
5
{% else %}
6
​
7
<span>Regular Price {{ price }}
8
​
9
{% endif %}
Copied!
Loops - how to iterate on lists
1
<ul>
2
{% for i in list %}
3
<li>{{ i }}</li>
4
{% endfor %}
5
</ul>
Copied!
Imports - components reuse
This feature is useful when we code large projects where parts of the UI are common to many pages, like the footer, top navigation, ..etc.
1
<h1>Django Templates</h1>
2
<p>
3
This is just a simple file served from the "templates" directory.
4
</p>
5
​
6
{% include "includes/footer.html" %} <-- Import directive
Copied!
Template Inheritance - allows to extend template with specific information
Template inheritance empowers the developer to build a base template that contains the common elements of your site and defines blocks that child templates can override like page title, highlight the active menu and other things specific to the current page.
Base Template Sample - saved as base.html in the templates directory
1
<html>
2
<head>
3
<title>My Django {% block title %}{% endblock %} </title>
4
</head>
5
<body>
6
<div class="container">
7
<h2>This is from the base template</h2>
8
<br>
9
{ block content }{ endblock }
10
<br>
11
</div>
12
</body>
13
</html>
Copied!
Child template - that extends the base template
1
{ extends "base.html" }
2
​
3
{ block title } MySample { endblock }
4
​
5
{ block content }
6
Cool content here
7
{ endblock }
Copied!
When Django loads child.html, the { extends } block informs the engine to merge the base.html template with the content provided by child.html.
    { block title } becomes MySample
    { block content } becomes Cool content here

​

Django Template Sample

All the above concepts can be seen in action by accessing a simple Django seed project built on top of the latest Bootstrap version: Pixel UI Django. This simple Django template can be downloaded and used for hobby and commercial products - for more information, please access:
Pixel Lite - Open-Source Django Template
​

Resources

Last modified 4mo ago