Open In App

Django Templates

Last Updated : 15 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the backend, templates are used to render dynamic content and define the visual structure of a web page.

Django provides two ways to organize templates, depending on the project's size and structure:

  • A project-level template directory, shared across all apps.
  • App-level template directories, useful in large projects or when different layouts are needed for different apps.

Template Setup in Django

In this guide, we’ll create a single template directory at the project level for simplicity. This means all templates will be stored in one central location.

Configuration in settings.py

To configure templates, open the settings.py file of your project. Create a folder named templates in the base directory (BASE_DIR) and update the TEMPLATES setting as follows:

Python
TEMPLATES = [
    {
        # Template backend to be used, For example Jinja
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
      
        ## Path definition of templates folder .
        'DIRS': [BASE_DIR/'templates'],
      
        'APP_DIRS': True,
        # options to configure
        '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',
            ],
        },
    },
]

Using Django Templates

Let's look at an example to understand how Django templates work with views and URLs. Templates are not limited to displaying static HTML- they can also present dynamic data passed from views via a context dictionary.

Refer to the following articles to check how to create a project and an app in Django. 

Consider an example project called "geeksforgeeks" with an app named "geeks":

views.py

We’ll define three views in geeks/views.py:

  • simple_view: Renders geeks.html with static content.
  • check_age: Processes a form input to check a user's age using conditional rendering.
  • loop: Sends a list and a string to loop.html for iteration.
Python
from django.shortcuts import render
from .forms import AgeForm

def simple_view(request):
    data = {"content": "Gfg is the best"}
    return render(request, "geeks.html", data)

def check_age(request):
    age = None
    if request.method == 'POST':
        # request.POST.get returns a string, default to "0"
        age = int(request.POST.get('age', 0))
    return render(request, 'check_age.html', {'age': age})

def loop(request):
    data = "Gfg is the best"
    number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    context = {
        "data": data,
        "list": number_list
    }
    return render(request, "loop.html", context)

urls.py

Define the URL patterns in your app’s urls.py file to link each view to a specific route:

Python
from django.urls import path
from mini import views  # Assuming your app is named 'mini'

urlpatterns = [
    path('simple', views.simple_view),
    path('condition', views.check_age),
    path('loop', views.loop),
]

Template Files

geeks.html

Displays the message passed from the simple_view.

Location: "app_name/templates/geeks.html"

HTML
<!DOCTYPE html>
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>Homepage</title> 
</head> 
<body> 
    <h1>Welcome to GeeksforGeeks.</h1> 
    <p>{{ data }}</p>
</body> 
</html>

check_age.html

Accepts user input and displays a message based on the entered age using if conditions.

Location: "app_name/templates/check_age.html"

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Age Checker</title>
</head>
<body>
    <h1>Welcome to the Age Checker</h1>

    <form method="post">
        {% csrf_token %}
        <label for="age">Enter your age:</label>
        <input type="number" id="age" name="age" required>
        <button type="submit">Check Age</button>
    </form>

    {% if age is not None %}
        <p>Your age is: {{ age }}</p>
        {% if age >= 20 %}
            <p>You are an adult.</p>
        {% else %}
            <p>You are not an adult.</p>
        {% endif %}
    {% endif %}
</body>
</html>

loop.html

Uses a for loop and if condition to display even numbers from a list.

Location: "app_name/templates/loop.html"

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Even Numbers</title>
</head>
<body>
    <h1>{{ data }}</h1>
    <p>Even Numbers:</p>
    <ul>
        {% for number in list %}
            {% if number|divisibleby:2 %}
                <li>{{ number }}</li>
            {% endif %}
        {% endfor %}
    </ul>
</body>
</html>

Output:

django_simple
Snapshot of /simple endpoint
django_condition
Snapshot of /condition endpoint
django_loop
Snapshot of /loop endpoint

Note: You can also follow the convention app_name/templates/app_name/template_name.html and then reference it in views as app_name/template_name.html. This is the traditional and recommended structure.

The Django template language

This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments. 

Jinja Variables

Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template. Syntax:

{{ variable_name }}

Example: Variables are surrounded by {{ and }} like this:  

My first name is {{ first_name }}. My last name is {{ last_name }}. 

With a context of {'first_name': 'Naveen', 'last_name': 'Arora'}, this template renders to: 

My first name is Naveen. My last name is Arora.

To know more about Django Template Variables visit - variables – Django Templates 

Jinja Tags

Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags. Syntax:

 {% tag_name %}

Example: Tags are surrounded by {% and %} like this:

{% csrf_token %}

Most tags accept arguments, for example : 

{% cycle 'odd' 'even' %}
 Commonly used Tags 
Commentcycleextends
iffor loopfor … empty loop
Boolean Operatorsfirstofinclude
loremnowurl

Filters

Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need. Syntax:

{{ variable_name | filter_name }}

Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags. Example:

{{ value | length }}

If value is ['a', 'b', 'c', 'd'], the output will be 4

 Major Template Filters 
addaddslashescapfirst
centercutdate
defaultdictsortdivisibleby
escapefilesizefodivisible byrmatfirst
joinlastlength
line numberslowermake_list
randomsliceslugify
timetimesincetitle
unordered_listupperwordcount

Comments

Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. Syntax:

{% comment 'comment_name' %}
{% endcomment %}

Example :

{% comment "Optional note" %}
    Commented out text with {{ create_date|date:"c" }}
{% endcomment %}

To know more about using comments in Templates, visit comment – Django template tags 

Template Inheritance

The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables. Syntax:

{% extends 'template_name.html' %} 

Example: Assume the following directory structure:

dir1/
    template.html
    base2.html
    my/
        base3.html
base1.html

In template.html, the following paths would be valid: 

HTML
{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}

To know more about Template inheritance and extends, visit extends – Django Template Tags 
 


Next Article
Practice Tags :

Similar Reads