Django Templates

Filed Under: Django

In this tutorial, we’ll learn what is Django Templates. We’ll later implement them in a simple Python Web Application.

Quick Django Setup

Let’s follow the steps from Django tutorial to set up our Virtual Environment, Django Project and Django App from the command line terminal quickly.

Goto the directory where you want to create the new Project and run the following commands sequentially.

$mkdir DjangoWorld
$cd DjangoWorld
$virtualenv -p /usr/local/bin/python3 env
$source env/bin/activate
$pip3 install django
$django-admin startproject TemplateProject .
$django-admin startapp TemplateApp
$python3 migrate
$python3 runserver

Add TemplateApp to the file present in the TemplateProject. I am using Atom IDE for this tutorial.

django template settings

Create a new folder template inside the Django App directory – TemplateApp. Inside the template folder we’ll create our html files.

Our final project structure of the web application looks like this:

django templates project structure

We need to create a file in the TemplateApp too. There we’ll define the URL patterns for the app.

We need to include that URL file in our TemplateProject file present in TemplateProject folder.

urlpatterns = [
    re_path(r'^', include('TemplateApp.urls')) # tell django to read in TEMPLATESapp

Django Templates

In our previous tutorial, we’d set the HTML code in our file of the Django App.

In the file, we can write the following design code for the Django website;

def current_datetime(request):
    today =
    html = "<html><body>It is today %s.</body></html>" % today
    return HttpResponse(html)

Hardcoding HTML code in the Python code isn’t the best way to build a website.

HTML codes can go to thousands of lines. We don’t wish to write those 1000 lines in our Python code since they aren’t related to Python in any way. It’ll become very hard to manage such projects.

This is where Django Templates will come to our rescue.

Django Templates are basic HTML code which includes Django Template Language. This special syntax is used to pass values from the Django Views python classes to the HTML codes.

How is the data from the passed to the Templates?

Using Render functions. Render functions are used in place of HttpResponse to display data in Django Templates.

A render function consists of three things:

  • Request instance
  • Path to html file
  • Context

The context in Django Templates is like a Dictionary. It consists of key-value pairs that are passed from the Django View to the Django Template.

Django Template Language

Variables are defined as : {{ variable }}. The variable is passed in the Context key.

      Hello {{variable}}</p>

This template is called from the Django view:

def hello(request):
   variable = 'Anupam'
   return render(request, "hello.html", {'variable' : variable})

Django Template Filters

We can modify the variable in the Django Templates using the filter. Filter is set after a | character.

{{variable|upper}} – Displays the value of the variable in uppercase.

{{variable|slice:":-5"}} removes the last 5 characters from the variable.

Django Template Tags

Tags in Django Templates are used for expressions. if elif, for loops are typically used.
A Tag is defined like:
{% tag %} – In place of tag you can set your expression.

It is required to start and close the tag as shown below:

{% for x in python_list %}
    <li>{{ }}</li>
{% endfor %}

if elif – else

% if python_list|length > 10 %}
    <h2>Number of rows: {{ python_list|length }}</h2>
  {% elif story_list|length == 1 %}
    <h2>One row</h2>
  {% else %}
    <p>No rows<p>
  {% endif %}

Creating Django Web Application

First, goto in the TemplateProject and add the path to the template directory in the TEMPLATE list on the DIR key.

django python templates settings template path

The django.contrib.admin templates are written in DTL. There is a popular alternative for DTL, namely jinja2 but we’ll discuss that some other time.

We’ll be crHTMLng three html pages in our web application – home, about and more.html.

First set the url patterns in the file present in the TemplateApp folder as shown below:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^about/$', views.about, name='about'),
    url(r'^more/$', views.MorePageView.as_view(), name='more'),

Here views refers to the file.

MorePageView is a Python class in which we define the Template as a View instead of rendering.

You can use either of Rendering function or TemplateViews.

The code for the file is given below.

from django.shortcuts import render
from django.http import HttpResponse

from django.views.generic import TemplateView

# # Create your views here.
def home(request):
    return render(request,'home.html',{})

data = [
{'name': '','link': ''},
{'name': 'Android ListView','link': ''},
{'name': 'Android RecyclerView','link': ''},
{'name': 'Android P Features','link': ''},
{'name': 'More...','link': 'more.html'},

def about(request):
    context = {'data_list' : data}
    return render(request,'about.html',context)

class MorePageView(TemplateView):
    template_name = "more.html"

Make sure you stick to a consistent indentation since Python is indentation sensitive.

We’re passing no Context to the home.html Django Template.

The about function renders the about.html template. In it, we pass a Python Dictionary of urls of some Android Tutorial along with an internal link to the more.html project.

In the Python class above, we’re directly invoking the Django Template through it’s class name. We’re not passing any Context.

If you want to pass Context using this method of TemplateView, do the following:

class MorePageView(TemplateView):
    def get(self, request, **kwargs):
        context = {'data_list' : data}
        return render(request, 'more.html', context)

The get method returns the list of all templates.

Let’s look at each of the Django Template Html files below:


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <h1>Our First Template</h1>
    We'll be covering the following features:
    <li>Rendering Templates from Views</li>
    <li>Passing data to Templates from Views</li>
    <li>Django Template Syntax</li>
<a href="{% url 'about' %}">About</a>


At the bottom, we provide a link to the about.html page using Django Template tags. {% url 'name_defined_in_urls' %}.

We’ve used Automatic URL reverse lookup since the names are already defined in the file.
This makes it short and concise.


<html lang="en">
    <meta charset="UTF-8">
    <title>About Us</title>
  This webpage consists of some of the JournalDev tutorial external links:

    <li>Checkout the logic to differentiate external and internal links.</li>
    <li>Django Templates has for loops for you.</li>

  {% for data in data_list %}

  {% if '.html' in %}
        <a href="{% url|slice:":-5" %}">{{|upper }} </a>
  {% else %}
        <a href="{{ }}" target="_self">{{ }} </a>
  {% endif %}

  {% endfor %}

<a href="{% url 'home' %}">Go Home</a>


In the above code, we check if the URL is external or internal.

If it is an external url, we set target = _self in the a href.

Otherwise using the slice operator we remove the extension from the Django Variable and do a url reverse lookup.

The code for the more.html file is given below:

<html lang="en">
    <meta charset="UTF-8">
  That's all for now.
  See you later. <br>

<a href="{% url 'about' %}">About</a> <a href="{% url 'home' %}">Home</a>

On your terminal run the command python3 runserver:
django python templates run on localhost

The output in your web browser should be like:
django template tutorial output

So in this tutorial, we made a Django Web Application in which we could pass a Python List of external and internal url links to the Django Templates and play around with them.

You can download the source code from the link below. Just go inside the root directory and set the virtual environment and activate it. Your web application would be ready.

Generic selectors
Exact matches only
Search in title
Search in content