Templates in Django

Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language.

The Render Function

This function takes three parameters −

  • Request − The initial request.
  • The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables.
  • Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view.

Django Template Language (DTL)

Django’s template engine offers a mini-language to define the user-facing layer of the application.

Displaying Variables

A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let's change our hello.html to display today’s date −

hello.html

<html>
   
   <body>
      Hello World!!!<p>Today is {{today}}</p>
   </body>
   
</html>

Then our view will change to −

def hello(request):
   today = datetime.datetime.now().date()
   return render(request, "hello.html", {"today" : today})

We will now get the following output after accessing the URL/myapp/hello −

Hello World!!!
Today is Sept. 11, 2015

As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}.

Filters

They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}.

Some examples −

  • {{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words.
  • {{string|lower}} − Converts the string to lowercase.
  • {{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags.

You can also set the default for a variable.

Tags

Tags lets you perform the following operations: if condition, for loop, template inheritance and more.

Tag if

Just like in Python you can use if, else and elif in your template −

<html>
   <body>
   
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today.day == 30 %}
      
      the last day of month.
      {% else %}
      
      I don't know.
      {%endif%}
      
   </body>
</html>

In this new template, depending on the date of the day, the template will render a certain value.

Tag for

Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template −

def hello(request):
   today = datetime.datetime.now().date()
   
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})

The template to display that list using {{ for }} −

<html>
   <body>
      
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today.day == 30 %}
      
      the last day of month.
      {% else %}
      
      I don't know.
      {%endif%}
      
      <p>
         {% for day in days_of_week %}
         {{day}}
      </p>
		
      {% endfor %}
      
   </body>
</html>

And we should get something like −

Hello World!!!
Today is Sept. 11, 2015
We are I don't know.
Mon
Tue
Wed
Thu
Fri
Sat
Sun

Block and Extend Tags

A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab.

Let’s change the hello.html template to inherit from a main_template.html.

main_template.html

<html>
   <head>
      
      <title>
         {% block title %}Page Title{% endblock %}
      </title>
      
   </head>
	
   <body>
   
      {% block content %}
         Body content
      {% endblock %}
      
   </body>
</html>

hello.html

{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today.day == 30 %}

the last day of month.
{% else %}

I don't know.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}

In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code −

In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title).

Comment Tag

The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code.

 

 

 

#######################################################

Tags

if/else

The {% if %} tag evaluates a variable, and if that variable is “True” (i.e., it exists, is not empty, and is not a false Boolean value), the system will display everything between {% if %} and {% endif %}, for example:

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% endif %}

An {% else %} tag is optional:

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% else %}
    <p>Get back to work.</p>
{% endif %}

Make sure to close each {% if %} with an {% endif %}, otherwise Django will throw a TemplateSyntaxError.

The if tag may also take one or several {% elif %} clauses as well:

{% if athlete_list %}
    <p>Number of athletes: {{ athlete_list|length }}</p>
{% elif athlete_in_locker_room_list %}
    <p>Athletes should be out of the locker room soon!</p>
{% elif ...
...
{% else %}
    <p>No athletes.</p>
{% endif %}

The {% if %} tag accepts andor, or not for testing multiple variables, or to negate a given variable. For example:

{% if athlete_list and coach_list %}
    <p>Both athletes and coaches are available.</p>
{% endif %}

{% if not athlete_list %}
    <p>There are no athletes.</p>
{% endif %}

{% if athlete_list or coach_list %}
    <p>There are some athletes or some coaches.</p>
{% endif %}

{% if not athlete_list or coach_list %}
    <p>There are no athletes or there are some coaches.</p>
{% endif %}

{% if athlete_list and not coach_list %}
    <p>There are some athletes and absolutely no coaches.</p>
{% endif %}

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or  e.g.:

{% if athlete_list and coach_list or cheerleader_list %}

will be interpreted like:

if (athlete_list and coach_list) or cheerleader_list

Multiple uses of the same logical operator are fine, but you can’t combine different operators. For example, this is valid:

{% if athlete_list or coach_list or parent_list or teacher_list %}

The {% if %} also accepts in / not in for testing whether a given value is or isn’t in the specified container, and is / is not for testing if two entities are the same object.

For example:

{% if "bc" in "abcdef" %}
    This appears since "bc" is a substring of "abcdef"
{% endif %}

{% if user not in users %}
    If users is a list, this will appear if user isn't an element of the list.
{% endif %}

{% if somevar is True %}
    This appears if and only if somevar is True.
{% endif %}

{% if somevar is not None %}
    This appears if somevar isn't None.
{% endif %}

for

The {% for %} tag allows you to loop over each item in a sequence. As in Python’s forstatement, the syntax is for X in Y, where Y is the sequence to loop over and X is the name of the variable to use for a particular cycle of the loop. Each time through the loop, the template system will render everything between {% for %} and {% endfor %}. For example, you could use the following to display a list of athletes given a variable athlete_list:

<ul>
    {% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
    {% endfor %}
</ul>

Add reversed to the tag to loop over the list in reverse:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

It’s possible to nest {% for %} tags:

{% for athlete in athlete_list %}
<h1>{{ athlete.name }}</h1>
<ul>
    {% for sport in athlete.sports_played %}
    <li>{{ sport }}</li>
    {% endfor %}
</ul>
{% endfor %}

If you need to loop over a list of lists, you can unpack the values in each sub list into individual variables.

For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points:

{% for x, y in points %}
    <p>There is a point at {{ x }},{{ y }}</p>
{% endfor %}

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

A common pattern is to check the size of the list before looping over it, and outputting some special text if the list is empty:

{% if athlete_list %}
    {% for athlete in athlete_list %}
        <p>{{ athlete.name }}</p>
    {% endfor %}
{% else %}
    <p>There are no athletes. Only computer programmers.</p>
{% endif %}

Because this pattern is so common, the for tag supports an optional {% empty %}clause that lets you define what to output if the list is empty. This example is equivalent to the previous one:

{% for athlete in athlete_list %}
    <p>{{ athlete.name }}</p>
{% empty %}
    <p>There are no athletes. Only computer programmers.</p>
{% endfor %}

There is no support for “breaking out” of a loop before the loop is finished. If you want to accomplish this, change the variable you’re looping over so that it includes only the values you want to loop over.

Similarly, there is no support for a “continue” statement that would instruct the loop processor to return immediately to the front of the loop. (See the section “Philosophies and Limitations” later in this chapter for the reasoning behind this design decision.)

Within each {% for %} loop, you get access to a template variable called forloop. This variable has a few attributes that give you information about the progress of the loop:

  • forloop.counter is always set to an integer representing the number of times the loop has been entered. This is one-indexed, so the first time through the loop, forloop.counter will be set to 1. Here’s an example:
    {% for item in todo_list %}
        <p>{{ forloop.counter }}: {{ item }}</p>
    {%endfor %}
  • forloop.counter0 is like forloop.counter, except it’s zero-indexed. Its value will be set to 0 the first time through the loop.
  • forloop.revcounter is always set to an integer representing the number of remaining items in the loop. The first time through the loop, forloop.revcounterwill be set to the total number of items in the sequence you’re traversing. The last time through the loop, forloop.revcounter will be set to 1.
  • forloop.revcounter0 is like forloop.revcounter, except it’s zero-indexed. The first time through the loop, forloop.revcounter0 will be set to the number of elements in the sequence minus 1. The last time through the loop, it will be set to 0.
  • forloop.first is a Boolean value set to True if this is the first time through the loop. This is convenient for special-casing:
    {% for object in objects %}
        {% if forloop.first %}
            <li class="first">
        {% else %}
            <li>
        {% endif %}
        {{ object }}</li>
    {% endfor %}
  • forloop.last is a Boolean value set to True if this is the last time through the loop. A common use for this is to put pipe characters between a list of links:
    {% for link in links %}
        {{ link }}{% if not forloop.last %} | {% endif %}
    {% endfor %}

    The above template code might output something like this:

      Link1 | Link2 | Link3 | Link4

    Another common use for this is to put a comma between words in a list:

    <p>Favorite places:</p>
    {% for p in places %}
        {{ p }}{% if not forloop.last %}, {% endif %}
    {% endfor %}
  • forloop.parentloop is a reference to the forloop object for the parent loop, in case of nested loops. Here’s an example:
      {% for country in countries %}
      <table>
          {% for city in country.city_list %}
          <tr>
              <td>Country #{{ forloop.parentloop.counter }}</td>
              <td>City #{{ forloop.counter }}</td>
              <td>{{ city }}</td>
          </tr>
          {% endfor %}
      </table>
      {% endfor %}

The forloop variable is only available within loops. After the template parser has reached {% endfor %}forloop disappears.

ifequal/ifnotequal

Comments

Just as in HTML or Python, the Django template language allows for comments. To designate a comment, use {# #}:

{# This is a comment #}

The comment will not be output when the template is rendered. Comments using this syntax cannot span multiple lines. This limitation improves template parsing performance.

In the following template, the rendered output will look exactly the same as the template (i.e., the comment tag will not be parsed as a comment):

This is a {# this is not
a comment #}
test.

If you want to use multi-line comments, use the {% comment %} template tag, like this:

{% comment %}
This is a
multi-line comment.
{% endcomment %}

The comment tag may contain an optional note (e.g. to explain why that section of code has been commented out):

{% comment "This is the optional note" %}
    ...
{% endcomment %}

Comment tags cannot be nested.

Filters

As explained earlier in this chapter, template filters are simple ways of altering the value of variables before they’re displayed. Filters use a pipe character, like this:

{{ name|lower }}

This displays the value of the {{ name }} variable after being filtered through the lowerfilter, which converts text to lowercase. Filters can be chained – that is, they can be used in tandem such that the output of one filter is applied to the next.

Here’s an example that takes the first element in a list and converts it to uppercase:

{{ my_list|first|upper }}

Some filters take arguments. A filter argument comes after a colon and is always in double quotes. For example:

{{ bio|truncatewords:"30" }}

This displays the first 30 words of the bio variable.

The following are a few of the most important filters. Appendix E covers the rest.

  • addslashes: Adds a backslash before any backslash, single quote, or double quote. This is useful for escaping strings. For example:{{ value|addslashes }}.
  • date: Formats a date or datetime object according to a format string given in the parameter. For example: {{ pub_date|date:"F j, Y" }}Format strings are defined in Appendix E.
  • length: Returns the length of the value. For a list, this returns the number of elements. For a string, this returns the number of characters. If the variable is undefined, length returns 0.

Philosophies and Limitations

Now that you’ve gotten a feel for the Django Template Language (DTL), it’s probably time to explain the basic design philosophy behind the DTL.

First and foremost, the limitations to the DTL are intentional.

Django was developed in the high volume, ever-changing environment of an online newsroom. The original creators of Django had a very definite set of philosophies in creating the DTL.

These philosophies remain core to Django today. They are:

  1. Separate logic from presentation
  2. Discourage redundancy
  3. Be decoupled from HTML
  4. XML is bad
  5. Assume designer competence
  6. Treat whitespace obviously
  7. Don’t invent a programming language
  8. Ensure safety and security
  9. Extensible

1. Separate logic from presentation

A template system is a tool that controls presentation and presentation-related logic – and that’s it. The template system shouldn’t support functionality that goes beyond this basic goal.

2. Discourage redundancy

The majority of dynamic web sites use some sort of common site-wide design – a common header, footer, navigation bar, etc. The Django template system should make it easy to store those elements in a single place, eliminating duplicate code. This is the philosophy behind template inheritance.

3. Be decoupled from HTML

The template system shouldn’t be designed so that it only outputs HTML. It should be equally good at generating other text-based formats, or just plain text.

4. XML should not be used for template languages

Using an XML engine to parse templates introduces a whole new world of human error in editing templates – and incurs an unacceptable level of overhead in template processing.

5. Assume designer competence

The template system shouldn’t be designed so that templates necessarily are displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of a limitation and wouldn’t allow the syntax to be as nice as it is.

Django expects template authors are comfortable editing HTML directly.

6. Treat whitespace obviously

The template system shouldn’t do magic things with whitespace. If a template includes whitespace, the system should treat the whitespace as it treats text – just display it. Any whitespace that’s not in a template tag should be displayed.

7. Don’t invent a programming language

The template system intentionally doesn’t allow the following:

  • Assignment to variables
  • Advanced logic

The goal is not to invent a programming language. The goal is to offer just enough programming-esque functionality, such as branching and looping, that is essential for making presentation-related decisions.

The Django template system recognizes that templates are most often written by designers, not programmers, and therefore should not assume Python knowledge.

8. Safety and security

The template system, out of the box, should forbid the inclusion of malicious code – such as commands that delete database records. This is another reason why the template system doesn’t allow arbitrary execution of Python code.

9. Extensibility

The template system should recognize that advanced template authors may want to extend its technology. This is the philosophy behind custom template tags and filters.

DTL Philosophy – Concluding Thoughts

Having worked with many different templating systems myself over the years, I whole-heartedly endorse this approach – the DTL and the way it has been designed is one of the major pluses of the Django framework.

When the pressure is on to Get Stuff Done, and you have both designers and programmers trying to communicate and get all the of the last minute tasks done, Django just gets out of the way and lets each team concentrate on what they are good at.

Once you have found this out for yourself through real-life practice, you will find out very quickly why Django really is the “framework for perfectionists with deadlines”.

More than any other component of web applications, template syntax is highly subjective, and programmers’ opinions vary wildly. The fact that Python alone has dozens, if not hundreds, of open source template-language implementations supports this point. Each was likely created because its developer deemed all existing template languages inadequate.

With all this in mind, Django is flexible – it does not require you to use the DTL. All of the most recent versions of Django, including Django 1.11, ship with the popular Jinja2template engine as well as the DTL to provide developers with options.

Because Django is intended to be a full-stack web framework that provides all the pieces necessary for web developers to be productive, most times it’s more convenient to use the DTL, but it’s not a strict requirement in any sense.

 

###############Geek
Django Templates
  • Last Updated : 10 Feb, 2020

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 an .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to end-user. Django mainly functions with a backend so, in order to provide 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 which 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,

 

 

 

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',
            ],
        },
    },
]

Using Django Templates

Illustration of How to use templates in Django using an Example Project. Templates not only show static data but also the data form different databases connected to the application through a context dictionary. Consider a project named geeksforgeeks having an app named geeks.

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

To render a template one needs a view and a url mapped to that view. Let’s begin by creating a view in geeks/views.py,

 

 

 

# import Http Response from django
from django.shortcuts import render
  
# create a function
def geeks_view(request):
    # create a dictionary to pass
    # data to the template
    context ={
        "data":"Gfg is the best",
        "list":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
    # return response with template and context
    return render(request, "geeks.html", context)

Now we need to map a URL to render this view,

 

 

 

from django.urls import path
 
# importing views from views..py
from .views import geeks_view 
 
urlpatterns = [
    path('', geeks_view),
]

Finally create a template in templates/geeks.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 Geeksforgeeks.</h1
    <p> Data  is {{  data }}</p>
    <h4>List is </h4>
    <ul>
    {% for i in list %}
    <li>{{ i }}</li>
    {% endfor %}
</body
</html

Let’s check if it is working,
django-templates

The Django template language

This is one of 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 loop in above example, we used it as a tag. similarly, we can used various other conditions such as if, else, if-else, empty, etc. Main characterisitcs of django Template language are Variables, Tags, Filters and Comments.

Variables

Variables outputs 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 accesses in 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

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
Comment cycle extends
if for loop for … empty loop
Boolean Operators firstof include
lorem now url

Filters

Django Template Engine provides filters are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify value of a variable whereas filters can be used for incrementing 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
add addslashes capfirst
center cut date
default dictsort divisibleby
escape filesizeformat first
join last length
linenumbers lower make_list
random slice slugify
time timesince title
unordered_list upper wordcount

Comments

Template ignores everything between {% comment %} and {% endcomment %}. 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
{% commment '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 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:

 

 

 

{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}
Django Template Filters
  • Difficulty Level : Basic
  • Last Updated : 07 Feb, 2020

Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify value of a variable whereas filters can be used for incrementing 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 in Django

This article revolves around various Django Template Filters one can use during a project. Filters transform the values of variables and tag arguments. Let’s check some major filters.

add addslashes capfirst
center cut date
default dictsort divisibleby
escape filesizeformat first
join last length
linenumbers lower make_list
random slice slugify
time timesince title
unordered_list upper wordcount
  1. add

    It is used to add an argument to the value.
    Example

    {{ value | add:"2" }}

    If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates.

  2. addslashes

    It is used to add slashes before quotes. Useful for escaping strings in CSV.
    Example

    {{ value | addslashes }}

    If value is “I’m Jai”, the output will be “I\’m Jai”.

  3. capfirst

    It is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.
    Example

    {{ value | capfirst }}

    If value is “jai”, the output will be “Jai”.

  4. center

    It is used to center the value in a field of a given width.
    Example

    "{{ value | center:"15" }}"

    If value is “Jai”, the output will be ” Jai “.cut

    It is used to remove all values of arg from the given string.

    Example

    {{ value | cut:" " }}

    If value is “String with spaces”, the output will be “Stringwithspaces”.

  5. date

    It is used to format a date according to the given format.
    Example

    {{ value | date:"D d M Y" }}

    If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here.

  6. default

    It is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself.

    Example

    {{ value | default:"nothing" }}

    If value is “” (the empty string), the output will be nothing.

  7. dictsort

    It takes a list of dictionaries and returns that list sorted by the key given in the argument.
    Example

    {{ value | dictsort:"name" }}

    If value is:

    [
        {'name': 'zed', 'age': 19},
        {'name': 'amy', 'age': 22},
        {'name': 'joe', 'age': 31},
    ]

    then the output would be:

    [
        {'name': 'amy', 'age': 22},
        {'name': 'joe', 'age': 31},
        {'name': 'zed', 'age': 19},
    ]
  8. divisibleby

    It returns True if the value is divisible by the argument.
    Example

    {{ value | divisibleby:"3" }}

    If value is 21, the output would be True.

  9. escape

    It is used to escapea a string’s HTML. Specifically, it makes these replacements:

    < is converted to <
    > is converted to >
    ' (single quote) is converted to '
    " (double quote) is converted to "
    & is converted to &

    Example

    {{ title | escape }}
  10. filesizeformat

    It is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).
    Example

    {{ value | filesizeformat }}

    If value is 123456789, the output would be 117.7 MB.

  11. first

    It is used to return the first item in a list.
    Example

    {{ value | first }}

    If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’.

  12. join

    It is used to join a list with a string, like Python’s str.join(list)
    Example

    {{ value | join:" // " }}

    If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”.

  13. last

    It is used to return the last item in a list.
    Example

    {{ value | last }}

    If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”.

  14. length

    It is used to return the length of the value. This works for both strings and lists.
    Example

    {{ value | length }}

    If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4.

  15. linenumbers

    It is used to display text with line numbers.
    Example

    {{ value | linenumbers }}

    If value is:

    one
    two
    three

    the output will be:

    1. one
    2. two
    3. three
  16. lower

    It is used to converts a string into all lowercase.
    Example

    {{ value | lower }}}

    If value is My Name is Jai, the output will be my name is jai.

  17. make_list

    It is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.
    Example

    {{ value | make_list }}

    If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’].

  18. random

    It is used to return a random item from the given list.
    Example

    {{ value | random }}

    If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”.

  19. slice

    It is used to return a slice of the list.
    Example

    {{ some_list | slice:":2" }}

    If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’].

  20. slugify

    It is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.
    Example

    {{ value | slugify }}

    If value is “Jai is a slug”, the output will be “jai-is-a-slug”.

  21. time

    It is used to format a time according to the given format.
    Example

    {{ value | time:"H:i" }}

    If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”.

  22. timesince

    It is used to format a date as the time since that date (e.g., “4 days, 6 hours”).

    Example

    {{ blog_date | timesince:comment_date }}

    if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”

  23. title

    It is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase.

    Example

    {{ value | title }}

    If value is “my FIRST post”, the output will be “My First Post”.

  24. nordered_list

    It is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.
    Example

    {{ var | unordered_list }}

    if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:

     

     

    <li>States
    <ul>
            <li>Kansas
            <ul>
                    <li>Lawrence</li>
                    <li>Topeka</li>
            </ul>
            </li>
            <li>Illinois</li>
    </ul>
    </li>
             </li>
  25. upper

    It is used to convert a string into all uppercase.
    Example

    {{ value | upper }}

    If value is “Jai is a slug”, the output will be “JAI IS A SLUG”.

  26. wordcount

    It is used to return the number of words.
    Example

    {{ value | wordcount }}

    If value is “jai is a slug”, the output will be 4.

Django Template Tags
  • Difficulty Level : Medium
  • Last Updated : 06 Feb, 2020

Django Web Framework ships with dozens of tags used to implement arbitrary logics right in the template. Tags look like this: {% tag %}. Tags are more complex than variables: Some create text in the output, some control flow by performing loops or logic, and some load external information into the template to be used by later variables. 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 in Django Templates

  1. Comment

    Template ignores everything between {% comment %} and {% endcomment %}. 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.
    Example

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

    To check more about comment tag, visit – comment – Django template tags

  2. cycle

    It produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth. Once all arguments are exhausted, the tag cycles to the first argument and produces it again.
    Example
    This tag is particularly useful in a loop:

     

     

     

    {% for o in some_list %} 
    <tr class="{% cycle 'row1' 'row2' %}"
    ... 
    </tr
    {% endfor %} 

    The first iteration produces HTML that refers to class row1, the second to row2, the third to row1 again, and so on for each iteration of the loop.
    To check more about cycle tag, visit – cycle – Django Template Tags

  3. extends

    extends tag is used for 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.
    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:

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

    To check more about extends tag, visit – extends – Django Template Tags

  4. if

    The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output.Example

     

     

     

    {% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
    {% elif athlete_in_locker_room_list %}
    Athletes should be out of the locker room soon!
    {% else %}
    No athletes.
    {% endif %}

    In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable.

    As one can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional.

    To check more about if tag, visit – if – Django Template Tags

  5. for loop

    for tag loops over each item in an array, making the item available in a context variable.
    Example
    For example, to display a list of athletes provided in athlete_list:

     

     

     

    <ul>
    {% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
    {% endfor %}
    </ul>

    To check more about for loop tag, visit – for loop – Django Template Tags

  6. for … empty loop

    for tag loops over each item in an array, making the item available in a context variable. The for tag can take an optional {% empty %} clause whose text is displayed if the given array is empty or could not be found. This is basically used as a condition to be followed to check if queryset is empty and what action to be performed in the same scenario.

    Example

     

     

     

    <ul
    {% if athlete_list %} 
    {% for athlete in athlete_list %} 
    <li>{{ athlete.name }}</li
    {% endfor %} 
    {% else %} 
    <li>Sorry, no athletes in this list.</li
    {% endif %} 
    </ul

    To check more about for … empty loop tag, visit – for … empty loop – Django Template Tags

  7. Boolean Operators

    The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag.

    Example

     

     

     

    <ul
    {% if variable boolean_operator value %}
    // statements
    {% endif %}
    </ul

    To check more about Boolean Operators, visit – Boolean Operators – Django Template Tags

  8. firstof

    firstof tag Outputs the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are “false”.

    Example

    {% firstof var1 var2 var3 %}

    This is equivalent to:

    {% if var1 %}
        {{ var1 }}
    {% elif var2 %}
        {{ var2 }}
    {% elif var3 %}
        {{ var3 }}
    {% endif %}

    One can also use a literal string as a fallback value in case all passed variables are False:

    {% firstof var1 var2 var3 "fallback value" %}

    To check more about firstof tag, visit – firstof – Django Template Tags

  9. include

    include tag loads a template and renders it with the current context. This is a way of “including” other templates within a template. The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.

    Example

    {% include "foo/bar.html" %}

    Normally the template name is relative to the template loader’s root directory. A string argument may also be a relative path starting with ./ or ../ as described in the extends tag.

    To check more about include tag, visit – include – Django Template Tags

  10. lorem

    lorem tag displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates.

    Example

    • {% lorem %} will output the common “lorem ipsum” paragraph.
    • {% lorem 3 p %} will output the common “lorem ipsum” paragraph and two random paragraphs each wrapped in HTML tags.
    • {% lorem 2 w random %} will output two random Latin words.

    To check more about lorem tag, visit – lorem – Django Template Tags

  11. now

    now tag displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section.
    Example

    It is {% now "D d M Y" %}

    Above tag will display, Tue 04 Feb 2020

    To check more about now tag, visit – now – Django Template Tags

  12. url

    url tag Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates.
    Example

    {% url 'some-url-name' v1 v2 %}

    The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL.

Boolean Operators

== operator
Equality. Example:

{% if somevar == "x" %}
  This appears if variable somevar equals the string "x"
{% endif %}

!= operator
Inequality. Example:

{% if somevar != "x" %}
  This appears if variable somevar does not equal the string "x",
  or if somevar is not found in the context
{% endif %}

< operator
Less than. Example:

{% if somevar < 100 %}
  This appears if variable somevar is less than 100.
{% endif %}

> operator
Greater than. Example:

 

 

{% if somevar > 0 %}
  This appears if variable somevar is greater than 0.
{% endif %}

<= operator
Less than or equal to. Example:

{% if somevar <= 100 %}
  This appears if variable somevar is less than 100 or equal to 100.
{% endif %}

>= operator
Greater than or equal to. Example:

{% if somevar >= 1 %}
  This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}

in operator
Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted:

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}
{% if "hello" in greetings %}
  If greetings is a list or set, one element of which is the string
  "hello", this will appear.
{% endif %}
{% if user in users %}
  If users is a QuerySet, this will appear if user is an
  instance that belongs to the QuerySet.
{% endif %}

not in operator
Not contained within. This is the negation of the in operator.

is operator
Object identity. Tests if two values are the same object. Example:

{% if somevar is True %}
  This appears if and only if somevar is True.
{% endif %}

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}

is not operator
Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example:

{% if somevar is not True %}
  This appears if somevar is not True, or if somevar is not found in the
  context.
{% endif %}

{% if somevar is not None %}
  This appears if and only if somevar is not None.
{% endif %}



for loop – Django Template Tags
  • Difficulty Level : Easy
  • Last Updated : 05 Feb, 2020

A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow paassing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends etc.
This article revolves about how to use for tag in Templates. for tag loops over each item in an array, making the item available in a context variable.

Syntax
{% for i in list %}
{% endfor %}
Example

For example, to display a list of athletes provided in athlete_list:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

for – Django template Tags Explanation

Illustration of How to use for tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks.

Now create a view through which we will pass the context dictionary,
In geeks/views.py,

 

# import Http Response from django
from django.shortcuts import render
 
# create a function
def geeks_view(request):
    # create a dictionary
    context = {
        "data" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    }
    # return response
    return render(request, "geeks.html", context)

Create a url path to map to this view. In geeks/urls.py,

from django.urls import path
 
# importing views from views.py
from .views import geeks_view
 
urlpatterns = [
    path('', geeks_view),
]

Create a template in templates/geeks.html,

 

{% for i in data %}
    <div class="row">
        {{ i }}
    </div>
{% endfor %}

Let’s check what is displayed on “/” are displayed in the template.
cycle-django-template-tags
Anything enclosed between for tag would be repeated, the number of times the loop is run.

Advanced Usage

One can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this:

 

{% for o in some_list %}
    <tr class="{% cycle rowvalue1 rowvalue2 %}">
        ...
    </tr>
{% endfor %}

Advanced Usage

One can loop over a list in reverse by using {% for obj in list reversed %}.

If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x, y) coordinates called points, you could use the following to output the list of points:

{% for x, y in points %}
    There is a point at {{ x }}, {{ y }}
{% endfor %}

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

 

##################################

mywebsite/myapp/hello2.html

<html>

<body>
Hello World!!!<p>n is {{n}}</p>
If is not working with >
{% if n == 70 %}

GRADE A
{% elif n > 60 %}

GRADE B
{% else %}

FAILED
{%endif%}

# For loop is working fine with dictionary
<p>
{% for day in days %}
{{day}}
</p>

{% endfor %}
</body>

</html>

mywebsite/myapp/views.py

def hello3(request,id):
return render(request, "hello2.html", {"n" : id, "days":["mon","tue","wed"]})

mywebiste/myapp/views.py

re_path('temp(\d+)', views.hello3,name='id'),

 

 

 

 

####################hello.html############

<html>

<body>

Today is {{data}}

{% comment %}

{# DICTIONARY #}
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
{# #}
{% endcomment %}

{# LIST #}

{% if data %}

{% for x in data %}
<p>List value {{ x }}</p>
{{ forloop.counter }}
{% empty %}
<p>There are no athletes. Only computer programmers.</p>

{% endfor %}

{% else %}
<p>There are no athletes. Only computer programmers.</p>
{% endif %}

 

 

{# {% if data['today'] == 1 %} #}

Hello World!!!<p>Today is {{today}}</p>

{# {%endif%} #}

</body>

</html>

#######################

def hello3(request,id):
print("day:",id)
# Dictionary
#d={"today" : id,"next":23}
#return render(request, "hello.html", {"data" : d})

# List
d={1,2,3,4,5,6}
#d=[]
return render(request, "hello.html", {"data" : d})