Django Templates

Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs.

  • We can use a single template directory which will be spread over the entire project.
  • For each app of our project, we can create a different template directory.

For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.

Configuration

Django Templates can be configured in app_name/settings.py,  

Python3




TEMPLATES = [
    {
        # Template backend to be used, For example Jinja  
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
          
        # directories for templates
        'DIRS': [],
        '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',
            ],
        },
    },
]


Now let’s create a template directory and add that directory in the above configuration. After creating the templates folder our directory should look like this – 

Let’s add the location of this directory in our templates dictionary.

Python3




TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        
        # adding the location of our templates directory
        'DIRS': [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',
            ],
        },
    },
]


After adding the location of the template directory we will create a simple HTML file and name it as index.html and then we will render this file from our view function.

HTML file:

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Homepage</title>
</head>
<body>
    <h1>Welcome to w3wiki</h1>
</body>
</html>


To render this HTML on our site we need to use the render function from the django.shortcuts. Below is the updated view function.

views.py

Python3




from django.shortcuts import render
  
# create a function
def geeks_view(request):
      
    return render(request, "index.html")


If we head to our website we will see the HTML data on our site as –

The Django Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Let’s see this with an example. We will try to render the content of our database dynamically to our website.

First, let’s update our views.py file. In this file we will get our data from our database and then pass this database as a dictionary to our HTML file.

views.py

Python3




from django.shortcuts import render
from .models import GeeksModel
  
# create a function
def geeks_view(request):
      
    content = GeeksModel.objects.all()
    context = {
        'content': content
    }
    return render(request, "index.html", context=context)


index.html

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Homepage</title>
</head>
<body>
  
    {% for data in content %}
    <h2>{{data.title}}</h2>
    <img src="{{ data.image.url }}" alt="">
      
<p><strong>Description:</strong>{{data.description}}</p>
  
      
<p><strong>Created On:</strong>{{data.created_on}}</p>
  
    {% endfor %}
  
</body>
</html>


Our website now looks like this – 

Now if we add more data to our site then that data will also be shown to our site without making any changes to our HTML or views.py. Let’s add some data and then see if it works or not.

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. 

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 }}

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 %}

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 }}

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 %}

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" %}


Refer to the below articles to get more information about Django Templates – 

Python Web Development With Django

Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.

Similar Reads

Why Django Framework?

Excellent documentation and high scalability. Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket, Dropbox, etc. and the list is never-ending. Easiest Framework to learn, rapid development, and Batteries fully included. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time. The last but not least reason to learn Django is Python, Python has a huge library and features such as Web Scraping, Machine Learning, Image Processing, Scientific Computing, etc. One can integrate all this with web applications and do lots and lots of advanced stuff....

Django Architecture

Django is based on MVT (Model-View-Template) architecture which has the following three parts –...

Setting up the Virtual Environment

Most of the time when you’ll be working on some Django projects, you’ll find that each project may need a different version of Django. This problem may arise when you install Django in a global or default environment. To overcome this problem we will use virtual environments in Python. This enables us to create multiple different Django environments on a single computer. To create a virtual environment type the below command in the terminal....

Installing Django

We can install Django using the pip command. To install this type the below command in the terminal....

Starting the project

To initiate a project of Django on Your PC, open Terminal and Enter the following command...

Project Structure

A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files-...

Creating an app

Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. Benefits of using Django apps –...

Django Views

...

Django URL Patterns

...

Django Models

A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page....

Uploading Images in Django

...

Render a model in Django Admin Interface

In Django, each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration). Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view....

Connecting Django to different Database

...

Django Templates

...

Django Forms

To tackle the above-said problem Django provides something called Django Models....

More on Django

...

Django Projects

...