Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Introduction to Django Templates

In this guide, you will learn about the Django templates and the language constructs that are necessary to build a Django application.

Nov 18, 2020 • 7 Minute Read

Introduction

In the Django MTV model, the template is the presentation layer. This layer interacts with the user, sends the requests to the views, and responds to the user.

Django templates deal with HTML/CSS/JS. All rendering is handled in templates. Other than the basic constructs of HTML/CSS/JS, Django comes with templating language to render dynamic data in the form of templates. In this guide, you will learn about the Django templates and the language constructs that are necessary to build a Django application.

Why Django Templates

Django template is a text document or Python string marked up that uses Django template language. Django keeps the logic and code separate from the design. It is essential to know that Django templates do not contain the embedded code of Python into HTML.

Django templates follow the DRY (do not repeat yourself) design principle, which requires developers to not repeat while designing a Django application. Django templates employ several other notions, such as template inheritance, tags, variables, filters, comments, etc.

Template Configuration

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

      import os

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]
    

Alternatively, you can maintain a template folder for each app separately. If you are maintaining the template for every app separately, you don't need to update the DIRS in settings.py. Make sure that your app is added in INSTALLED_APPS in settings.py .

The Django Template Language

In the Django template language, the syntax involves four major constructs.

1. Variables

Variables output the value from the context. The context is generally a dict-like object (mapping variable name with its respective value) passed from views.

The basic syntax is:

      {{ variable_name }}
    

For example, if you render the context set as shown below ...

      from django.shortcuts import render

def my_view(request):
    context = {
        "author": "Gaurav Singhal",
        "website": {
            "domain": "https://pluralsight.com",
            "views": 200
        },
        "odds": [1, 3, 5]
    }
    return render(request, "index.html", context)
    

... you can access it in template index.html as :

      {{author}}
{{website.domain}}
{{website.views}}
    

2. Tags

Tags give logic to the template language to render the content logically.

The basic syntax is:

      {% tag_name %}
    

Example:

      {% if user.is_authenticated %}Howdy, {{ user.username }}, How are you {% endif %}
    

There are several tags which are used in templates Some of them are:

  • If/Else:

    {% if condition %} 
    	renders if body 
    {% else %} 
        renders else body 
    {% endif %}
    
    • For loop

      {% for odd in odds %}
      {{odd}}
      {% endfor %}
      
      • include

This is used to load a template and render it to the current context. It is very useful for creating several components separately, such as navbar, footer, etc., and then including them in several templates.

      {% include template_name %}
    
  • block

This defines the block to be overridden by the child template. You will get a better idea of blocks when we discuss template inheritance .

      {% block content %}
{% endblock %}
    

You can read more about built-in tags in the Django docs.

3. Filters

The filter is used to transform the value of the variable and tag argument.

It can be used as:

      {{ my_variable | filter }}
    

For example:

      {{ my_date|date:"Y-m-d" }}
    

You can read more about filter and several built-in filters in the Django docs.

4. Comments

You can easily add a comment in Django templates:

      {# Comment here. It won't be rendered #}
    

Template Inheritance

One of the most powerful parts of the Django template engine is template inheritance. This allows you to build a base skeleton template that contains all the base/common elements and defines blocks in a child/derived template after extending the base template. It is easier to understand in practice. Let's first create a base.html.

      <html>
   <head>
      <title>
         {% block title %}Base title{% endblock %}
      </title>
        {% comment %} This Bootsrap css is added to all pages {% endcomment %}
      <link rel="stylesheet" href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
   </head>
   <body>
    <p>
    Body content which remains in all the pages
    </p>
      {% block content %}
         Body content
      {% endblock %}
   </body>
</html>
    

Now create a child template and save it as index.html.

      {% extends 'base.html' %}

{% block title %}
This is index title
{% endblock title %}

{% block content %}
Main content of index.html
{% endblock content %}
    

Now when you render the index.html from the views, you will get the following output:

      Body content which remains in all the pages

Main content of index.html
    

Conclusion

A Django template deals with passing information from a Django view to the browser and is considered the basic building block of a dynamic Django application. You can refer to the Django documentation to learn Django template in depth.

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

Learn More

Explore these Django courses from Pluralsight to continue learning: