In the last tutorial, we have discussed the built-in if tag in the Django Template System.
The if tag can be associated with an optionalelse tag, where the if tag corresponds to the if conditional statement which is used when we want to test a condition for a boolean value - true or false and the else tag corresponds to the
else in the if-else conditional statement.
Note: Instead of a condition, there could even be a variable which returns a non-zero value or just a non-zero value.
Working of if/else tag
The if tag starts with the {% if %} tag and ends with a {% endif %} tag.
The else tag starts with the {% else %} tag and if an else tag is associated with an if tag, it must be placed before the ending tag of if tag i.e. {% endif %} tag.
All the texts between the start and end tag is known as a block.
Let us see a code with syntax of an if tag with an optional else else tag.
{% if var %}
<p>This is associated with the if tag </p>
{% else %}
<p>This is associated with the else tag </p>
{% endif %}
As you can see in the code above, the {% if %} block evaluates the value of a variable, var, if the value of this variable is True, the Django template system only displays the statements before the {% else %} tag and does not display anything between the {% else %} and {% endif %} tag.
If the value of variable evaluated by the {% if %} block turns out of to be False then everything between the {% else %} and {% endif %} tag is displayed.
Note:
While we could use relational and logical operators with the if tag, we cannot use relational or logical operators with the optional else tag to test a condition expression involving variables.
Django project with if/else tag
Up next, we are going to explain a situation is which the Django Template System encounters the if tag and its associated else tag in an executing HTML template file.
For those who don't know how to create a Django Project from a scratch and have not read our previous tutorials, here is a recap.
Creating a Django project
To create a directory for our project, we need to open the Command Prompt and type in the command -
django-admin startproject django_proj1
dhago-admin is a management utility for Django Framework, using which we could create a new project and much more.
startproject is a command to start a new Django project.
django_proj1 is the name of our Django project and also the name of our project directory created in the current directory.
The startproject command gives us a sub-directory and files
Executing the startproject command has not only created a project directory named django_proj1, but has also created a file manage.py and another sub-directory
with the same name as the project directory, which also contains some Python files -
django_proj1 is the root directory of our Django project, also known as the container of our project.
manage.py is a command-line utility which allows us to interact with Django project in various ways.
django_proj1 sub-directory is actually a Python package for our project. We can import this package(a group of modules) and its contents just like we import any general Python package/module and its contents.
__init__.py is a file which allows our sub-directory django_proj1 to be treated as a Python package.
settings.py is a file used for setting the configurations for our Django project.
urls.py is a file used to specify the URL declarations for our Django project, also known as a a table of contents.
wsgi.py is a file used as an entry-point for WSGI web-servers to serve your project.
Starting the development server
After creating the project directory and the files required to run our Django project, it is time to execute the Django Development Server. To do this,
we will have to open the command prompt, change the current directory to the root directory of our Django project and execute the following command.
python manage.py runserver
Executing the above mentioned command will trigger the Django Development Server in action, as you can see in the picture below.
Note: Please ignore the warning of unapplied database migrations for now, we will talk more about it later in the section - Database with Django.
Now that you have successfully started the Django development server, it is time to visit the http://127.0.0.1:8000/ link and you will see a webpage displaying a congratulatory message, as shown below.
Note: The runserver command runs the Django development server at the port 8000.
Creating an app in our project
A project may contain one or multiple applications. As we have already created a project, now let us create an application which compares the values of two variables using the if tag of Django Template System. This application will be created right under our root - project directory django_proj1.
To create an application, we have to open the command prompt, change the current directory to the root directory of our Django project and execute the following command -
python manage.py startapp compare
The command startapp in combination with manage.py utility is used to create an app of a project, using which we have created an app named - compare.
Executing the startapp command has not only created an application directory named compare in the root - project directory, but has also created the following set of Python files -
Next, we are going to create an HTML template file for this application.
Creating an HTML template file for our app.
Next, we are going to create an HTML template file within our application folder compare, we will name this file template.htm.
template.htm
<html>
<head><title>Django Template System - Decodejava.com</title></head>
<body>
<b>var1 = {{ var1 }}</b> <br/>
<b>var2 = {{ var2 }}</b> <br/>
<b>var3 = {{ var3 }}</b> <br/>
{% if var1 < var2 %}
<p><i>var1 is smaller than var2 </i></b>
{% else %}
<p><i>var1 is not smaller than var2 </i></b>
{% endif %}
{% if var1 > var2 %}
<p><i>var1 is greater than var2 </i></p>
{% else %}
<p><i>var1 is not greater than var2 </i></p>
{% endif %}
{% if var1 <= var2 %}
<p><i>var1 is less than or equal to var2 </i></p>
{% else %}
<p><i>var1 is not less than or not equal to var2 </i></p>
{% endif %}
{% if var1 >= var2 %}
<p><i>var1 is greater than or equal to var2 </i></p>
{% else %}
<p><i>var1 is not greater than or not equal to var2 </i></p>
{% endif %}
{% if var1 == var2 %}
<p><i>var1 is equal to var2 </i></p>
{% else %}
<p><i>var1 is not equal to var2 </i></p>
{% endif %}
{% if var1 != var2 %}
<p><i>var1 is not equal to var2 </i></p>
{% else %}
<p><i>var1 is equal to var2 </i></p>
{% endif %}
{% if var1 < var2 and var1 < var3 %}
<p><i>var1 is less than var2 and var1 is less than var3 </i></p>
{% else %}
<p><i>var1 is not less than var2 and var1 is not less than var3 </i></p>
{% endif %}
{% if var1 < var2 or var3 < var2 %}
<p><i>var1 is less than var2 or var3 is less than var2 </i></p>
{% else %}
<p><i>var1 is not less than var2 or var3 is not less than var2 </i></p>
{% endif %}
{% if not var1 > var2 %}
<p><i>var1 is not greater than var2 </i></p>
{% else %}
<p><i>var1 is greater than var2 </i></p>
{% endif %}
{% if a != a %}
<p><i>a is not equal to a </i></b>
{% else %}
<p><i>a is equal to a </i></b>
{% endif %}
{% if 'hi' != 'hi' %}
<p><i>hi is not equal to hi </i></b>
{% else %}
<p><i>hi is equal to hi </i></b>
{% endif %}
{% if 'hello world' != "hello world" %}
<p><i>hello world is not equal to hello world </i></b>
{% else %}
<p><i>hello world is equal to hello world </i></b>
{% endif %}
{% if zero == 0 %}
<p><i>zero is equal to 0 </i></b>
{% else %}
<p><i>zero is not equal to 0</i></b>
{% endif %}
</body>
</html>
In this HTML template file, we are using if template tags with associated else template tags to compare the values of variables var1, var2 and var3 as well as some hard-coded values by using different relational and logical operators. The variables are defined in the view function(we are going to create it next).
Creating a view function for the app
Once we have created the HTML template file in the application, we will also need to create a view function associated with it. A view function is simply a Python function which takes an HttpRequest from the HTML template file and returns an HttpResponse with the values of the variables specified and requested by the HTML template file.
Note: This view function is defined in the file view.py, which is already created and stored in our application directory, compare. Let us just copy and paste the following code in view.py.
We have named this view function - tag_lookup().
view.py
from django.shortcuts import render
import datetime
def tag_lookup(request):
#Creating a dictionary of key-value pairs
dic = { 'var1' : 100,
'var2' : 200,
'var3' : 300 }
#Calling the render() method to render the request from template_ex.htm page by using the dictionary, dic
return render(request, "template_ex.htm", dic)
Understanding the code in view.py :
First, we have imported the render function from the django.shortcuts module and next we have imported the datetime module.
Next, we have defined a view function named - templ, which takes an HttpRequest object in its parameter and we have named this parameter - request.
Note:Each view function takes an HttpRequest object in its first parameter and it could named anything but its typically named - request.
In the view function, we have simply created a dictionary(dic) of items of key:value pairs, where each key(e.g. var1, var2) is assigned a value
Note:In the HTML template file, each key is used as a variable name to access the its value specified in the dictionary(dic).
To initiate the process of rendering, we call the render() method, which replaces variables in HTML template file with their values, which are looked up in the Context(a parameter to the render() method).
The render() method requires three parameters passed to it:
Request - An incoming request.
Path to the HTML template - This is a path relative to the path specified in settings.py file.
Context - Since, Django 1.8+ version, the render() method takes a Context, which should be represented by a dictionary of items needed in the template.
On call, the render() method renders the request from template_ex.htm page by using the items of dictionary(dic), and it has returned an HttpResponse object with the rendered text, which is then eventually returned back by the view function - tag_lookup().
Mapping URL to view
After creating the view function of an application, we need to specify the mapping between a URL and this view function in a file named - urls.py. The file urls.py is simply coded in Python and we will have to create the urls.py file in the folder of our application, compare.
The use of mapping a URL to the view function is, when this URL is requested by the user, its mapped view function is executed and a response is returned.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.tag_lookup),
]
As you can see in the file urls.py, we have imported the path() function from the module django.urls.
The path() function has been passed the two must arguments -
An empty string to specify the URL pattern, specified by ' '.
This URL pattern specified in the application's urls.py file is the relative path to the template. This path gets added to another URL pattern, specified in the project's urls.py file(we are going to create it next), and the combined path will be matched to the view function - tag_lookup defined in the application's views.py.
Pointing the project url to application url
Next, we are going to point the project url(urls.py) to the application url(urls.py) by using the include() function. For this, we will open the file urls.py in the root - project directory, django_proj1, and copy-paste the following code.
urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('tags', include('compare.urls')),
]
As you can see in the file urls.py, we have imported the path() and include() function from the module django.urls.
The path() function has been passed the two must arguments -
A string to specify the URL pattern - 'tags/'. This is the relative path to the template.
This URL pattern, combined with the URL pattern defined in the application's urls.py will be matched to the view function - tag_lookup, which is specified in the application urls.py file( stored in the application directory compare). Therefore we have used the include() function to include and refer to the application's urls.py file.
How to load the HTML template file.
Before we finally execute the project, we must load the above created HTML template template.htm, which is stored within our application folder compare.
To load the HTML template file, we need to specify its full path in the configuration file - settings.py, which is stored in the project folder. For our example, you can find this file in the sub-directory django_proj1 within our project django_proj1 i.e. - django_proj1/django_proj1/settings.py.
Within the settings.py file, you need to locate the property DIRS and copy-paste the full-path to the HTML template file against it, as shown below and save the file.
'DIRS': ['E:/django_proj1/compare/'],
Executing the application of our project
To execute the compare application of our project django_proj1, we just have to enter the address - http://127.0.0.1:8000/tags/.
As you can see in the picture, the string tags/ in the URL is the URL-pattern which gets matched to the URL pattern specified in the project urls.py file, which calls the application's urls.py and its associated view function - tag_lookup(in the application) is executed and its response is displayed.
The response displays the result of using the if template tags with else template tags in HTML Template file to compare the values of variables var1, var2 and var3 and also hard-coded values using the relational and logical operators, where the variables are defined in the view function.