Book Image

Django: Web Development with Python

By : Aidas Bendoraitis, Samuel Dauzon, Arun Ravindran
Book Image

Django: Web Development with Python

By: Aidas Bendoraitis, Samuel Dauzon, Arun Ravindran

Overview of this book

Data science is hot right now, and the need for multitalented developers is greater than ever before. A basic grounding in building apps with a framework as minimalistic, powerful, and easy-to-learn as Django will be a useful skill to launch your career as an entrepreneur or web developer. Django is a web framework that was designed to strike a balance between rapid web development and high performance. This course will take you on a journey to become an efficient web developer thoroughly understanding the key concepts of Django framework. This learning path is divided into three modules. The course begins with basic concepts of the Django framework. The first module, Django Essentials, is like a practical guide, filled with many real-world examples to build highly effective Django web application. After getting familiar with core concepts of Django, it's time to practice your learning from the first module with the help of over 90 recipes available in this module. In the second module, Web Development with Django Cookbook, you'll learn varying complexities to help you create multilingual, responsive, and scalable websites with Django. By the end of this module, you will have a good understanding of the new features added to Django 1.8 and be an expert at web development processes.The next step is to discover the latest best practices and idioms in this rapidly evolving Django framework. This is what you'll be learning in our third module, Django Design Patterns and Best Practices. This module will teach you common design patterns to develop better Django code. By the end of the module, you will be able to leverage the Django framework to develop a fully functional web application with minimal effort.
Table of Contents (6 chapters)

Chapter 4. Working with Templates

As we saw in the first chapter, where we explained the MVC and MVT models, templates are files that will allow us to generate the HTML code returned to the client. In our views, the HTML code is not mixed with the Python code.

Django comes with its own template system. However, as Django is modular, it is possible to use a different template system. This system is composed of a language that will be used to make our dynamic templates.

In this chapter, we will learn how to do the following:

  • Send data to a template
  • Display data in a template
  • Display object lists in a template
  • Handle chains with filters in Django
  • Use URLs effectively
  • Create base templates in order to extend other templates
  • Insert static files in our templates

Displaying Hello world! in a template

We will create the first template of our application. To do so, we must first edit the settings.py file to define the folder that will contain our templates. We will first define the project folder as PROJECT_ROOT to simplify the migration to another system:

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, '../TasksManager/templates'),
  # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
  # Always use forward slashes, even on Windows.
  # Don't forget to use absolute paths, not relative paths.
)

Now that Django knows where to look for the templates, we will create the first template of the application. To do this, use a file browser and add the index.html file in the TasksManager/templates/en/public/ folder. We do not need to create the __init__.py file, because these files do not contain any Python files.

The following is the content of the index.html file:

<html>
  <head>
    <title>
      Hello World Title
    </title>
  </head>
  <body>
    <h1>
      Hello World Django
    </h1>
    <article>
      Hello world !
    </article>
  </body>
</html>

Although the template is correct, we need to change the view to indicate its use. We will modify the index.py file with the following content:

from django.shortcuts import render
# View for index page. 
def page(request):
  return render(request, 'en/public/index.html')

If we test this page, we will notice that the template has been taken into account by the view.

Injecting the data from the view to the template

Before improving our template, we must send variables to the templates. The injection of the data is based on these variables, as the template will perform certain actions. Indeed, as we have seen in the explanation of the MVC pattern, the controller must send variables to the template in order to display them.

There are several functions to send variables to the template. The two main functions are render() and render_to_response(). The render() function is very similar to render_to_response (). The main difference is that if we use render, we do not need to specify context_instance = RequestContext(request) in order to send the current context. This is the context that will allow us to use the CSRF middleware later in the book.

We will change our view to inject variables in our template. These variables will be useful to work with the template language. The following is our modified view:

from django.shortcuts import render
"""
View for index page. 
"""

def page(request):
  my_variable = "Hello World !"
  years_old = 15
  array_city_capitale = [ "Paris", "London", "Washington" ]
  return render(request, 'en/public/index.html', { "my_var":my_variable, "years":years_old, "array_city":array_city_capitale })

Creating dynamic templates

Django comes with a full-template language. This means that we will use template tags that will allow us to have more flexibility in our templates and display variables, perform loops, and set up filters.

The HTML and template languages are mixed in the templates; however, the template language is very simplistic, and there is a minority when compared to the HTML code. A web designer will easily modify the template files.

Integrating variables in templates

In our controller, we send a variable named my_var. We can display it in a <span> tag in the following way. Add the following lines in the <article> tag of our template tag:

<span> {{my_var}} </ span> 

In this way, because our variable contains string = "Hello World!", the HTML code that will be generated is as follows:

<span> Hello World! </span>

We will learn how to create conditions for variables or functions in order to filter the data in the variables in the following examples.

Conditional statements

Language templates also allow conditional structures. Note that for a display variable, double brackets {{}} are used, but once we have an action to be made as a condition or loop, we will use {%%}.

Our controller sends a years variable that can define age. An example of a conditional structure is when you can change the value of the variable in the controller to observe the changes. Add the following code in our <article> tag:

<span>
  {% if years < 10 %}
    You are a child
  {% elif years < 18 %}
    You are a teenager
  {% else %}
    You are an adult!
  {% endif %}
</span>

In our case, when we send the value 15 to the generated template, the code that is used is as follows:

<span> You are a teenager </span>

Looping in a template

Looping allows you to read through the elements of a table or data dictionary. In our controller, we sent a data table called array_city in which we have the names of cities. To see all these names of cities in the form of a list, we can write the following in our template:

<ul>
  {% for city in array_city %}
    <li>
      {{ city }}
    </li>
  {% endfor %}
</ul>

This looping will go through the array_city table, and place each element in the city variable that we display in the <li> tag. With our sample data, this code will produce the following HTML code:

<ul>
  <li>Paris</li>
  <li>London</li>
  <li>Washington</li>
</ul>

Conditional statements

Language templates also allow conditional structures. Note that for a display variable, double brackets {{}} are used, but once we have an action to be made as a condition or loop, we will use {%%}.

Our controller sends a years variable that can define age. An example of a conditional structure is when you can change the value of the variable in the controller to observe the changes. Add the following code in our <article> tag:

<span>
  {% if years < 10 %}
    You are a child
  {% elif years < 18 %}
    You are a teenager
  {% else %}
    You are an adult!
  {% endif %}
</span>

In our case, when we send the value 15 to the generated template, the code that is used is as follows:

<span> You are a teenager </span>

Looping in a template

Looping allows you to read through the elements of a table or data dictionary. In our controller, we sent a data table called array_city in which we have the names of cities. To see all these names of cities in the form of a list, we can write the following in our template:

<ul>
  {% for city in array_city %}
    <li>
      {{ city }}
    </li>
  {% endfor %}
</ul>

This looping will go through the array_city table, and place each element in the city variable that we display in the <li> tag. With our sample data, this code will produce the following HTML code:

<ul>
  <li>Paris</li>
  <li>London</li>
  <li>Washington</li>
</ul>

Looping in a template

Looping allows you to read through the elements of a table or data dictionary. In our controller, we sent a data table called array_city in which we have the names of cities. To see all these names of cities in the form of a list, we can write the following in our template:

<ul>
  {% for city in array_city %}
    <li>
      {{ city }}
    </li>
  {% endfor %}
</ul>

This looping will go through the array_city table, and place each element in the city variable that we display in the <li> tag. With our sample data, this code will produce the following HTML code:

<ul>
  <li>Paris</li>
  <li>London</li>
  <li>Washington</li>
</ul>

Using filters

Filters are an effective way to modify the data before sending it to the template. We will look at some examples of filters in the following sections to understand them better.

The upper and lower filters

The lower filter converts into lowercase letters, and the upper filter converts into uppercase letters. The example given in the subsequent sections contains the my_hello variable, which equals Hello World!

The lower filter

The code for the lower filter is as follows:

<span> {{ my_hello | lower }} </span>

This code generates the following HTML code:

<span> hello world! </span>

The upper filter

The code for the upper filter is as follows:

<span> {{ my_hello | upper }} </span>

This code generates the following HTML code:

<span> HELLO WORLD! </span>

The capfirst filter

The capfirst filter transforms the first letter to uppercase. The example with the myvar = "hello" variable is as follows:

<span>{{ my_hello | capfirst }}</span>

This code generates the following HTML code:

<span> Hello World! </span>

The pluralize filter

The pluralize filter can easily handle plurals. Often, developers choose a simple solution for lack of time. The solution is to display channels: You have 2 products in your cart.

Django simplifies this kind of string. The pluralize filter will add a suffix to the end of a word if the variable represents a plural value, shown as follows:

You have {{ product }} nb_products {{ nb_products | pluralize }} in our cart.

This channel will show the following three channels if nb_products is 1 and 2:

You have 1 product in our cart.
You have 2 products in our cart.
I received {{ nb_diaries }} {{ nb_diaries|pluralize : "y , ies "}}.

The previous code will show the following two chains if nb_diaries is 1 and 2:

I received one diary.
I received two diaries.

In the previous example, we used a filter that takes arguments for the first time. To set parameters to a filter, you must use the following syntax:

{{ variable | filter:"parameters" }}

This filter helps to increase the quality of your site. A website looks much more professional when it displays correct sentences.

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off

The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The upper and lower filters

The lower filter converts into lowercase letters, and the upper filter converts into uppercase letters. The example given in the subsequent sections contains the my_hello variable, which equals Hello World!

The lower filter

The code for the lower filter is as follows:

<span> {{ my_hello | lower }} </span>

This code generates the following HTML code:

<span> hello world! </span>

The upper filter

The code for the upper filter is as follows:

<span> {{ my_hello | upper }} </span>

This code generates the following HTML code:

<span> HELLO WORLD! </span>

The capfirst filter

The capfirst filter transforms the first letter to uppercase. The example with the myvar = "hello" variable is as follows:

<span>{{ my_hello | capfirst }}</span>

This code generates the following HTML code:

<span> Hello World! </span>

The pluralize filter

The pluralize filter can easily handle plurals. Often, developers choose a simple solution for lack of time. The solution is to display channels: You have 2 products in your cart.

Django simplifies this kind of string. The pluralize filter will add a suffix to the end of a word if the variable represents a plural value, shown as follows:

You have {{ product }} nb_products {{ nb_products | pluralize }} in our cart.

This channel will show the following three channels if nb_products is 1 and 2:

You have 1 product in our cart.
You have 2 products in our cart.
I received {{ nb_diaries }} {{ nb_diaries|pluralize : "y , ies "}}.

The previous code will show the following two chains if nb_diaries is 1 and 2:

I received one diary.
I received two diaries.

In the previous example, we used a filter that takes arguments for the first time. To set parameters to a filter, you must use the following syntax:

{{ variable | filter:"parameters" }}

This filter helps to increase the quality of your site. A website looks much more professional when it displays correct sentences.

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off

The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The lower filter

The code for the lower filter is as follows:

<span> {{ my_hello | lower }} </span>

This code generates the following HTML code:

<span> hello world! </span>

The upper filter

The code for the upper filter is as follows:

<span> {{ my_hello | upper }} </span>

This code generates the following HTML code:

<span> HELLO WORLD! </span>
The capfirst filter

The capfirst filter transforms the first letter to uppercase. The example with the myvar = "hello" variable is as follows:

<span>{{ my_hello | capfirst }}</span>

This code generates the following HTML code:

<span> Hello World! </span>
The pluralize filter

The pluralize filter can easily handle plurals. Often, developers choose a simple solution for lack of time. The solution is to display channels: You have 2 products in your cart.

Django simplifies this kind of string. The pluralize filter will add a suffix to the end of a word if the variable represents a plural value, shown as follows:

You have {{ product }} nb_products {{ nb_products | pluralize }} in our cart.

This channel will show the following three channels if nb_products is 1 and 2:

You have 1 product in our cart.
You have 2 products in our cart.
I received {{ nb_diaries }} {{ nb_diaries|pluralize : "y , ies "}}.

The previous code will show the following two chains if nb_diaries is 1 and 2:

I received one diary.
I received two diaries.

In the previous example, we used a filter that takes arguments for the first time. To set parameters to a filter, you must use the following syntax:

{{ variable | filter:"parameters" }}

This filter helps to increase the quality of your site. A website looks much more professional when it displays correct sentences.

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off
The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>
The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The upper filter

The code for the upper filter is as follows:

<span> {{ my_hello | upper }} </span>

This code generates the following HTML code:

<span> HELLO WORLD! </span>
The capfirst filter

The capfirst filter transforms the first letter to uppercase. The example with the myvar = "hello" variable is as follows:

<span>{{ my_hello | capfirst }}</span>

This code generates the following HTML code:

<span> Hello World! </span>
The pluralize filter

The pluralize filter can easily handle plurals. Often, developers choose a simple solution for lack of time. The solution is to display channels: You have 2 products in your cart.

Django simplifies this kind of string. The pluralize filter will add a suffix to the end of a word if the variable represents a plural value, shown as follows:

You have {{ product }} nb_products {{ nb_products | pluralize }} in our cart.

This channel will show the following three channels if nb_products is 1 and 2:

You have 1 product in our cart.
You have 2 products in our cart.
I received {{ nb_diaries }} {{ nb_diaries|pluralize : "y , ies "}}.

The previous code will show the following two chains if nb_diaries is 1 and 2:

I received one diary.
I received two diaries.

In the previous example, we used a filter that takes arguments for the first time. To set parameters to a filter, you must use the following syntax:

{{ variable | filter:"parameters" }}

This filter helps to increase the quality of your site. A website looks much more professional when it displays correct sentences.

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off
The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>
The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The capfirst filter

The capfirst filter transforms the first letter to uppercase. The example with the myvar = "hello" variable is as follows:

<span>{{ my_hello | capfirst }}</span>

This code generates the following HTML code:

<span> Hello World! </span>

The pluralize filter

The pluralize filter can easily handle plurals. Often, developers choose a simple solution for lack of time. The solution is to display channels: You have 2 products in your cart.

Django simplifies this kind of string. The pluralize filter will add a suffix to the end of a word if the variable represents a plural value, shown as follows:

You have {{ product }} nb_products {{ nb_products | pluralize }} in our cart.

This channel will show the following three channels if nb_products is 1 and 2:

You have 1 product in our cart.
You have 2 products in our cart.
I received {{ nb_diaries }} {{ nb_diaries|pluralize : "y , ies "}}.

The previous code will show the following two chains if nb_diaries is 1 and 2:

I received one diary.
I received two diaries.

In the previous example, we used a filter that takes arguments for the first time. To set parameters to a filter, you must use the following syntax:

{{ variable | filter:"parameters" }}

This filter helps to increase the quality of your site. A website looks much more professional when it displays correct sentences.

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off

The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The pluralize filter

The pluralize filter can easily handle plurals. Often, developers choose a simple solution for lack of time. The solution is to display channels: You have 2 products in your cart.

Django simplifies this kind of string. The pluralize filter will add a suffix to the end of a word if the variable represents a plural value, shown as follows:

You have {{ product }} nb_products {{ nb_products | pluralize }} in our cart.

This channel will show the following three channels if nb_products is 1 and 2:

You have 1 product in our cart.
You have 2 products in our cart.
I received {{ nb_diaries }} {{ nb_diaries|pluralize : "y , ies "}}.

The previous code will show the following two chains if nb_diaries is 1 and 2:

I received one diary.
I received two diaries.

In the previous example, we used a filter that takes arguments for the first time. To set parameters to a filter, you must use the following syntax:

{{ variable | filter:"parameters" }}

This filter helps to increase the quality of your site. A website looks much more professional when it displays correct sentences.

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off

The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The escape and safe to avoid XSS filters

The XSS filter is used to escape HTML characters. This filter helps prevent from XSS attacks. These attacks are based on injecting client-side scripting by a hacker. The following is a step-by-step description of an XSS attack:

  • The attacker finds a form so that the content will be displayed on another page, for example, a comment field of a commercial site.
  • The hacker writes JavaScript code to hack using the tag in this form. Once the form is submitted, the JavaScript code is stored in the database.
  • The victim views the page comments and JavaScript runs.

The risk is more important than a simple alert() method to display a message. With this type of vulnerability, the hacker can steal session IDs, redirect the user to a spoofed site, edit the page, and so on.

More concretely, the filter changes the following characters:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' is converted to '
  • " is converted to &quot;
  • & is converted to &amp;

We can automatically escape the contents of a block with the {% autoescape %} tag, which takes the on or off parameter. By default, autoescape is enabled, but note that with older versions of Django, autoescape is not enabled.

When autoescape is enabled, if we want to define a variable as a variable of trust, we can filter it with the safe filter. The following example shows the different possible scenarios:

<div>
  {% autoescape on %}
  <div>
    <p>{{ variable1 }}</p>
    <p>
      <span>
        {{ variable2|safe }}
      </span>
      {% endautoescape %}
      {% autoescape off %}
    </p>
  </div>
    <span>{{ variable3 }}</span>
    <span>{{ variable4|escape }}</span>
  {% endautoescape %}
  <span>{{ variable5 }}</span>
</div>

In this example:

  • variable1 is escaped by autoescape
  • variable2 is not escaped as it was filtered with safe
  • variable3 is not escaped because autoescape is defined as off
  • variable4 is escaped because it has been filtered with the escape filter
  • variable5 is escaped because autoescape is off

The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The linebreaks filter

The linebreaks filter allows you to convert line breaks into an HTML tag. A single new line is transformed into the <br /> tag. A new line followed by a blank will become a paragraph break ,</p>:

<span>{{ text|linebreaks }}</span>

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

The truncatechars filter

The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

The example of the variable that contains "Welcome in Django " is as follows:

{{ text|truncatechars:14 }}

This code outputs the following:

"Welcome in ..."

Creating DRY URLs

Before learning what a DRY link is, we will first remind you of what an HTML link is. Every day, when we go on the Internet, we change a page or website by clicking on links. These links are redirected to URLs. The following is an example link to google.com:

<a href="http://www.google.com">Google link !</a>

We will create a second page in our application to create the first valid link. Add the following line to the urls.py file:

url(r'^connection$', 'TasksManager.views.connection.page'),

Then, create a view corresponding to the preceding URL:

from django.shortcuts import render
# View for connection page. 
def page(request):
  return render(request, 'en/public/connection.html')

We will create a second template for the new view. Let's duplicate the first template and call the copy, connection.html, as well as modify Hello world in Connection. We can note that this template does not respect the DRY philosophy. This is normal; we will learn how to share code between different templates in the next section.

We will create an HTML link in our first index.html template. This link will direct the user to our second view. Our <article> tag becomes:

<article>
  Hello world !
  <br />
  <a href="connection">Connection</a>
</article>

Now, let's test our site with the development server, and open our browser to the URL of our site. By testing the site, we can check whether the link works properly. This is a good thing, because now you are able to make a static website with Django, and this framework includes a handy tool to manage URLs.

Django can never write a link in the href property. Indeed, by properly filing our urls.py file, we can refer to the name of a URL and name address.

To do this, we need to change our urls.py file that contains the following URLs:

url(r'^$', 'TasksManager.views.index.page', name="public_index"),
url(r'^connection/$', 'TasksManager.views.connection.page', name="public_connection"),

Adding the name property to each of our URLs allows us to use the name of the URL to create links. Change your index.html template to create a DRY link:

<a href="{% url 'public_connection' %}">Connection</a>

Test the new site again; note that the link still works. But for now, this feature is useless to us. If Google decides to improve the indexing of the URLs whose addresses end with the name of the website, you will have to change all the URLs. To do this with Django, all you will need to do is change the second URL as follows:

url(r'^connection-TasksManager$', 'TasksManager.views.connection.page', name="public_connection"),

If we test our site again, we can see that the change has been done properly and that the change in the urls.py file is effective on all the pages of the site. When you need to use parameterized URLs, you must use the following syntax to integrate the parameters to the URL:

{% url "url_name" param %}
{% url "url_name" param1, param2 %}

Extending the templates

The legacy of templates allows you to define a super template and a subtemplate that inherits from the super template. In the super template, it is possible to define blocks that subtemplates can fill. This method allows us to respect the DRY philosophy by applying the common code to several templates in a super template. We will use an example where the index.html template will extend the base.html template.

The following is the base.html template code, which we must create in the template folder:

<html>
  <head>
    <title>
      { block title_html %}{% endblock %}
    </title>
  </head>
  <body>
    <h1>
      Tasks Manager - {% block h1 %}{% endblock %}
    </h1>
    <article>
      {% block article_content %}{% endblock %}
    </article>
  </body>
</html>

In the previous code, we defined three areas that the child templates can override: title_html, h1, and article_content. The following is the index.html template code:

{% extends "base.html" %}
{% block title_html %}
  Hello World Title
{% endblock %}
{% block h1 %}
  {{ bloc.super }}Hello World Django
{% endblock %}
{% block article_content %}
  Hello world !
{% endblock %}

In this template, we first use the extends tag, which extends the base.html template. Then, the block and endblock tags allow us to redefine what is present in the base.html template. We may change our connection.html template in the same way so that a change in base.html can be made on both templates.

It is possible to define as many blocks as necessary. We can also create super templates that extend themselves to create more complex architectures.

Using static files in templates

Static files such as JavaScript files, CSS, or images are essential to obtain an ergonomic website. These files are often stored in a folder, but they can be useful to modify this folder under development or in production.

According to the URLs, Django allows us to define a folder containing the static files and to easily modify its location when required.

To set the path where Django will look for static files, we have to change our settings.py file by adding or changing the following line:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, '../TasksManager/static/'),
)

We will define a proper architecture for our future static files. It is important to choose an early consistent architecture, as it makes the application support as well as include another developer easier. Our statics files' architecture is as follows:

static/
  images/
  javascript/
    lib/
  css/
  pdf/

We create a folder for each type of static file and define a lib folder for JavaScript libraries as jQuery, which we will use later in the book. For example, we change our base.html file. We will add a CSS file to manage the styles of our pages. To do this, we must add the following line between </ title> and < / head>:

<link href="{% static "css/style.css" %}" rel="stylesheet" type="text/css" />

To use the tag in our static template, we must also load the system by putting the following line before using the static tag:

{% load staticfiles %}

We will create the style.css file in the /static/css folder. This way, the browser won't generate an error later in the development.

Summary

In this chapter, we learned how to create a template and send data to the templates, and how to use the conditions, loops, and filters in the templates. We also discussed how to create DRY URLs for a flexible URL structure, expand the templates to meet the DRY philosophy, and how to use the static files.

In the next chapter, we will learn how to structure our data to save it in a database.