In this tutorial, we’ll learn what is Django Templates. We’ll later implement them in a simple Python Web Application.
Table of Contents
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 manage.py migrate
$python3 manage.py runserver
Add TemplateApp to the settings.py
file present in the TemplateProject
. I am using Atom IDE for this tutorial.
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:
We need to create a urls.py
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 urls.py
file present in TemplateProject folder.
urlpatterns = [
re_path('admin/', admin.site.urls),
re_path(r'^', include('TemplateApp.urls')) # tell django to read urls.py in TEMPLATESapp
]
]
Django Templates
In our previous tutorial, we’d set the HTML code in our views.py
file of the Django App.
In the views.py file, we can write the following design code for the Django website;
def current_datetime(request):
today = datetime.datetime.now()
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 views.py 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.
<html>
<body>
Hello {{variable}}</p>
</body>
</html>
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.
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:
<ul>
{% for x in python_list %}
<li>{{ x.name }}</li>
{% endfor %}
</ul>
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 settings.py
in the TemplateProject and add the path to the template
directory in the TEMPLATE
list on the DIR
key.
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 urls.py
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 views.py 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 views.py 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': 'JournalDev.com','link': 'https://www.journaldev.com'},
{'name': 'Android ListView','link': 'https://www.journaldev.com/9247/android-listview-example-tutorial'},
{'name': 'Android RecyclerView','link': 'https://www.journaldev.com/10024/android-recyclerview-android-cardview-example-tutorial'},
{'name': 'Android P Features','link': 'https://www.journaldev.com/21178/android-p-features'},
{'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:
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Our First Template</h1>
<p>
We'll be covering the following features:
<ol>
<li>Rendering Templates from Views</li>
<li>Passing data to Templates from Views</li>
<li>Django Template Syntax</li>
</ol>
</p>
<a href="{% url 'about' %}">About</a>
</body>
</html>
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 urls.py file.
This makes it short and concise.
about.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About Us</title>
</head>
<body>
<p>
This webpage consists of some of the JournalDev tutorial external links:
<ol>
<li>Checkout the logic to differentiate external and internal links.</li>
<li>Django Templates has for loops for you.</li>
</ol>
</p>
{% for data in data_list %}
{% if '.html' in data.link %}
<p>
<a href="{% url data.link|slice:":-5" %}">{{ data.name|upper }} </a>
</p>
{% else %}
<p>
<a href="{{ data.link }}" target="_self">{{ data.name }} </a>
</p>
{% endif %}
{% endfor %}
<a href="{% url 'home' %}">Go Home</a>
</body>
</html>
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">
<head>
<meta charset="UTF-8">
<title>More</title>
</head>
<body>
That's all for now.
See you later. <br>
<a href="{% url 'about' %}">About</a> <a href="{% url 'home' %}">Home</a>
</body>
</html>
On your terminal run the command python3 manage.py runserver
:
The output in your web browser should be like:
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.