Django’s syntax elegantly blends Python and HTML to create dynamic websites. Python handles the backend logic, defining views to manage data requests and URL routing, while HTML templates, enhanced by Django’s templating language, provide the frontend presentation. These templates incorporate special tags that seamlessly integrate dynamic data fetched by the Python views. This Model-View-Controller (MVC) architecture promotes a clean separation of concerns, improving code organization, security, and scalability, making Django a powerful framework for building robust and maintainable web applications.

Variables in the template

Django templates dynamically display data using variables. Python views supply the information, and template tags ({{ variable_name }}) act as placeholders, making each page unique and responsive to the data.

Example

templates/template.html:

<h1>Hello {{ firstname }}, how are you?</h1>

Make a variable in view

Data for the firstname variable flowed from the view to the template.

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  context = {
    'firstname': 'Linus',
  }
  return HttpResponse(template.render(context, request))

context object, containing the necessary data, is created and passed as the first argument to the template.render() function within the view.

Make Variables in the Template

The {% with %} template tag lets you define variables directly within the template, accessible until {% endwith %}.

Example

templates/template.html:

{% with firstname="Tobias" %}
<h1>Hello {{ firstname }}, how are you?</h1>
{% endwith %}

Information from the Model

The aforementioned example demonstrated a simple method for creating and utilising variables in a template.

Typically, a model provides the majority of the external data that you wish to use in a template.

In the earlier chapters, we developed a model named Member, which we will utilise extensively in the upcoming tutorial chapters.

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Member

def testing(request):
  mymembers = Member.objects.all().values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))

The data is now integrated into the template.

templates/template.html:

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>

Tags for Django Templates

You may carry out programming logic, such as running for loops and if statements, with Django templates.

“Template tags” are what Django refers to as these keywords: if and for.

We enclose template tags in {% %} brackets to execute them.

Example

templates/template.html:

{% if greeting == 1 %}
  <h1>Hello</h1>
{% else %}
  <h1>Bye</h1>
{% endif %}

Code for Django

By using template tags, Django is informed that anything else than just HTML is about to be shown.

Before transmitting HTML to the client, we can perform some programming on the server thanks to the template tags.

templates/template.html:

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>

If Tag Django

If Statement

An if statement checks a variable’s value; if true, it runs a specific code block.

Example

{% if greeting == 1 %}
  <h1>Hello</h1>
{% endif %} 

Elif

elif conditions are evaluated sequentially after an initial if statement or preceding elif statements.

Example

{% if greeting == 1 %}
  <h1>Hello</h1>
{% elif greeting == 2 %}
  <h1>Welcome</h1>
{% endif %} 

Else

The else block is executed only when all preceding conditional expressions in an if-elif-else statement evaluate to false.

{% if greeting == 1 %}
  <h1>Hello</h1>
{% elif greeting == 2 %}
  <h1>Welcome</h1>
{% else %}
  <h1>Goodbye</h1>
{% endif %} 

Operators

The == operator, which is used in the examples above to determine whether a variable is equal to a value, is one of many operators you can employ. If you only want to determine whether a variable is not empty, you can even omit the operator:

Example

{% if greeting %}
  <h1>Hello</h1>
{% endif %} 

(==) Is equal to

Example

{% if greeting == 2 %}
  <h1>Hello</h1>
{% endif %} 

(!=) Is not equal to

Example

{% if greeting != 1 %}
  <h1>Hello</h1>
{% endif %} 

(<) Is less than

Example

{% if greeting < 3 %}
  <h1>Hello</h1>
{% endif %} 

(<=) Is less than, or equal to

Example

{% if greeting <= 3 %}
  <h1>Hello</h1>
{% endif %} 

(>) Is greater than

Example

{% if greeting > 1 %}
  <h1>Hello</h1>
{% endif %} 

(>=) Is greater than, or equal to

Example

{% if greeting >= 1 %}
  <h1>Hello</h1>
{% endif %} 

and

To assess the truth value of a conjunction of multiple Boolean expressions. The best option depends on the context and the level of detail needed.

Example

{% if greeting == 1 and day == "Friday" %}
  <h1>Hello Weekend!</h1>
{% endif %} 

or

To assess the truth value of a disjunction of Boolean expressions.

Example

{% if greeting == 1 or greeting == 5 %}
  <h1>Hello</h1>
{% endif %} 

and/or

Combine logical AND and OR operators.

Example

{% if greeting == 1 and day == "Friday" or greeting == 5 %}

It’s crucial to understand that brackets are inserted for and but not for or when combining and and or operators because Django does not permit them in if statements.

Meaning that the above example is read by the interpreter like this:

Example

{% if (greeting == 1 and day == "Friday") or greeting == 5 %}

in

To ascertain the presence of a specified element within a given object.

Example

{% if 'Banana' in fruits %}
  <h1>Hello</h1>
{% else %}
  <h1>Goodbye</h1>
{% endif %} 

not in

To see if an object excludes a particular item.

Example

{% if 'Banana' not in fruits %}
  <h1>Hello</h1>
{% else %}
  <h1>Goodbye</h1>
{% endif %} 

is

Ascertain the equivalence of two objects.

This operator differs from the == operator in that it verifies the identity of two objects, whereas the == operator verifies the values of two objects.

Within the view’s scope, objects x and y possess equivalent values.

views.py:

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  context = {
    'x': ['Apple', 'Banana', 'Cherry'], 
    'y': ['Apple', 'Banana', 'Cherry'], 
  }
  return HttpResponse(template.render(context, request))  

While having equal values, are these two objects actually the same object?

Example

{% if x is y %}
  <h1>YES</h1>
{% else %}
  <h1>NO</h1>
{% endif %}

For comparative purposes, let us re-evaluate the preceding example using the == operator.

Example

{% if x == y %}
  <h1>YES</h1>
{% else %}
  <h1>NO</h1>
{% endif %}

Two objects are considered identical (as opposed to merely equivalent) if and only if they share the same memory address. The is operator verifies this identity.

The functionality of creating variables within the template environment will be demonstrated using the {% with %} tag.

Example

{% with var1=x var2=x %}
  {% if var1 is var2 %}
    <h1>YES</h1>
  {% else %}
    <h1>NO</h1>
  {% endif %}
{% endwith %}

is not

Example

To verify that two objects are not the same object.

{% if x is not y %}
  <h1>YES</h1>
{% else %}
  <h1>NO</h1>
{% endif %} 

Categorized in: