Python

How to use Django Inclusion tag

Django framework uses different types of templates to present the data of the application. The Django admin interface uses the custom template tag. The looks of these interface elements, such as buttons, fields, etc., are the same for all pages. The Django developer can define the custom template tag and filter to the extent the template engine and the new template tag can be used using the {% custom_tag %}. The template tag that is used to display data by rendering another template is called the inclusion tag. The way of using the inclusion tag in the Django template is shown in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks.

A. Install the Django version 3+ on Ubuntu 20+ (preferably)
B. Create a Django project
C. Run the Django server to check the server is working correctly or not.

Setup a Django app:

A. Run the following command to create a Django app named inclusiontagapp.

$ python3 manage.py startapp inclusiontagapp

B. Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.

$ python3 manage.py createsuperuser

C. Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
    …..
    'inclusiontagapp'
]

D. Create a folder named templates inside the inclusiontagapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/django_pro/inclusiontagapp/templates'],
             ….
      },
]

Implement Inclusion Tag in Django:

Create templatetags folder inside the inclusiontagapp folder. Next, create a python file named inclusiontag.py with the following script. The template module is imported into the script to use the inclusion tag. A list of even numbers will be generated after calling the display_even_numbers() function of this script. The output of this script will be displayed in the display.html file that has been created in the next step of this tutorial.

inclusiontag.py

# Import template module
from django import template
# Create an object of Library()
register = template.Library()
# Define the template file for the inclusion tag
@register.inclusion_tag('display.html')

# Declare function to find out the even numbers within a range
def display_even_numbers(a, b):
    # Declare a empty list
    number = []
    # Iterate the loop to find out the even number between a and b
    for i in range(a, b):
        # Check the number is even or not
        if i % 2 == 0:
            # Add the number in the list if it is even
            number.append(i)
    # Return the list to the display.html file
    return {"output": number}

Create an HTML file named display.html inside the templates folder and add the following script. The list’s values returned by the inclusion tag are read by a for loop in the script.

display.html

<html>
<head>
    <title>
        Testing Inclusion Tag
    </title>
</head>
<body>
<ol>
    {% for val in output %}
    <li>
        {{ val }}
    </li>
    {% endfor %}
</ol>
</body>

</html>

Next, create another HTML file named incusiontag.html inside the templates folder and add the following script. In this script, the content of the inclusiontag made in the previous part of this tutorial is loaded, and the display_even_number() function is called with two argument values, 10 and 20. This function will create a list of even numbers between 10 and 20 and return the list to the display.html file.

inclusiontag.html

<html>
<head>
    <title>
        Django Inclusion Tag Example
    </title>
</head>
<body>
<center>
<h2 style="color:blue">List of even numbers from 10 to 20</h2>
{% load inclusiontag %}
{% display_even_numbers 10 20 %}
</center>
</body>
</html>

Modify the views.py file with the following script to load the inclusion tag in the required template file. When the function inclusiontag() of this script is called, it will display the inclusiontag.html file that will load the inclusiontag and call the display_even_numbers() function.

views.py

# Import renders module
from django.shortcuts import render

'''
Declare function to render inclusiontag.html file
to load inclusion tag
'''

def inclusiontag(request):
    return render(request, "inclusiontag.html")

Modify the urls.py file of the Django project and add the following script. After running the Django server, if the path, inctag, will be added after the base URL, the inclusiontag() function will be called from the view file. This function will render the inclusiontag.html file. This HTML file will load the inclusion tag that will call display_even_numbers() with arguments. This function will return a list of even numbers based on the argument values and display them in the display.html file.

urls.py

# Import path
from django.urls import path
# Import inclusiontag view
from inclusiontagapp.views import inclusiontag

# Define path to call the inclusiontag function of the view
urlpatterns = [
    path('inctag', inclusiontag),
]

Now, run the following command to start the Django server to check the above script is working correctly or not.

$ python3 manage.py runserver

Run the following URL from any browser to check the output of this app.

http://localhost:8000/inctag

The following output will appear if the above files are created and working properly. There are 5 even numbers between 10 to 20, and these have been displayed in the output.

Conclusion:

Many functions exist in the Django framework to create different types of custom tags. These are simple_tag(), inclusion_tag() and ssignment_tag(). simple_tag() function is used to return string after processing the data. inclusion_tag() function is used to return a template after processing the data. assignment_tag() function is used to set a variable after processing the data. The inclusion_tag() function has been shown in this tutorial that returned a rendered template after processing the data. I hope this tutorial will help the reader know how to use the inclusion tag in the Django app.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.