YouTip LogoYouTip

Django Template

Django Templates | Rookie Tutorial

Django's template system is a core component used to separate business logic (Python) from the presentation layer (HTML). It allows developers to dynamically generate HTML pages using simple tags and variables.

In the previous chapter, we used django.http.HttpResponse() to output "Hello World!". This approach mixes data with views, which contradicts Django's MVT philosophy.

In this chapter, we will introduce Django templates in detail. A template is a text file that separates a document's presentation from its content.

Feature Syntax/Example Use Case
Variable Rendering {{ variable }} Display dynamic data
Logic Control {% if %}, {% for %} Conditional/loop rendering
Template Inheritance {% extends %}, {% block %} Avoid repetitive HTML structure
Static Files {% static 'path' %} Load CSS/JS/images
Custom Filters @register.filter Extend template functionality

Template Usage Example

Continuing from the previous chapter's project, create a templates directory under the HelloWorld directory and create a file named .html. The full directory structure is as follows:

HelloWorld/
|-- HelloWorld
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py
|   |-- urls.pyc
|   |-- views.py
|   |-- views.pyc
|   |-- wsgi.py
|   `-- wsgi.pyc
|-- manage.py
`-- templates
    `-- .html

The code for .html is as follows:

Code for HelloWorld/templates/.html:

<h1>{{ hello }}</h1>

From the template, we can see that variables use double curly braces {{ }}.

Next, we need to tell Django the path to our template files. Open HelloWorld/HelloWorld/settings.py and modify the DIRS entry inside TEMPLATES to [BASE_DIR / "templates"], as shown below:

Code for HelloWorld/HelloWorld/settings.py:

...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "templates"],  # Modified line
        'APP_DIRS': True,
        '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',
            ],
        },
    },
]

...

Now, modify views.py to add a new object for passing data to the template:

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request):
    context = {}
    context['hello'] = 'Hello World!'
    return render(request, '.html', context)

As you can see, we now use render instead of the previously used HttpResponse. The render function also takes a dictionary called context as a parameter.

The key hello in the context dictionary corresponds to the variable {{ hello }} in the template.

Code for HelloWorld/HelloWorld/urls.py:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('/', views.),
]

Next, navigate to the HelloWorld directory and run the following command to start the server:

python3 manage.py runserver 0.0.0.0:8000

Visit again, and you should see the page:

Image 1

This completes our use of templates to output data, achieving separation between data and views.

Next, we'll introduce commonly used template syntax rules in detail.


Django Template Tags

Syntax:

{% tag %}

Used to control template logic. Common tags include:

Tag Purpose
{% for %} Loop through lists/dictionaries
{% if %} Conditional statements
{% extends %} Inherit from a base template
{% block %} Define content blocks that child templates can override
{% include %} Embed other template snippets
{% url %} Reverse URL resolution (avoids hard-coded paths)
{% csrf_token %} Generate CSRF token (used in POST forms)

Variables

Template syntax:

view: { "HTML variable name" : "views variable name" }
HTML: {{ variable name }}

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request): 
    views_name = "Rookie Tutorial"
    return render(request, ".html", {"name": views_name})

.html in templates:

<p>{{ name }}</p>

Image 2

Visit again, and you should see the page:

Image 3

Lists

In .html under templates, you can use dot notation with an index to retrieve corresponding elements.

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request):
    views_list = ["Rookie Tutorial 1", "Rookie Tutorial 2", "Rookie Tutorial 3"]
    return render(request, ".html", {"views_list": views_list})

Code for HelloWorld/templates/.html:

<p>{{ views_list }}</p>  <!-- Retrieve entire list -->
<p>{{ views_list.0 }}</p>  <!-- Retrieve first element of the list -->

Visit again, and you should see the page:

Image 4

Dictionaries

In .html under templates, you can use dot notation with a key to retrieve the corresponding value.

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request):
    views_dict = {"name": "Rookie Tutorial"}
    return render(request, ".html", {"views_dict": views_dict})

Code for HelloWorld/templates/.html:

<p>{{ views_dict }}</p>
<p>{{ views_dict.name }}</p>

Visit again, and you should see the page:

Image 5

Filters

Template syntax:

{{ variable_name|filter:optional_parameter }}

Template filters modify a variable before it is displayed. Filters use the pipe character (|), as shown below:

{{ name|lower }}

The variable {{ name }} is processed by the lower filter, converting uppercase letters to lowercase.

Filters can be chained, meaning the output of one filter becomes the input for the next:

{{ my_list|first|upper }}

The above example retrieves the first element and converts it to uppercase.

Some filters accept arguments. Filter arguments follow a colon and are always enclosed in double quotes. For example:

{{ bio|truncatewords:"30" }}

This displays the first 30 words of the bio variable.

Other filters:

  • addslashes: Adds backslashes before any backslash, single quote, or double quote.
  • date: Formats a date or datetime object according to a given format string. Example: {{ pub_date|date:"F j, Y" }}
  • length: Returns the length of the variable.

default

default provides a fallback value for a variable.

If the boolean value of the variable passed from the view is false, the specified default value is used.

The following values are considered false:

0 0.0 False 0j "" [] () set() {} None

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request):
    name = 0
    return render(request, ".html", {"name": name})

Code for HelloWorld/templates/.html:

{{ name|default:"Rookie Tutorial 666" }}

Visit again, and you should see the page:

Image 6

length

Returns the length of an object. Works for strings and lists.

For dictionaries, it returns the number of key-value pairs. For sets, it returns the length after deduplication.

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request):
    name = "Rookie Tutorial"
    return render(request, ".html", {"name": name})

Code for HelloWorld/templates/.html:

{{ name|length}}

Visit again, and you should see the page:

Image 7

filesizeformat

Displays file sizes in a human-readable format (e.g., '13 KB', '4.1 MB', '102 bytes').

For dictionaries, it returns the number of key-value pairs. For sets, it returns the length after deduplication.

Code for HelloWorld/HelloWorld/views.py:

from django.shortcuts import render

def (request):
    num = 1024
    return render(request, ".html", {"num": num})

Code for HelloWorld/templates/.html:

{{ num|filesizeformat}}

Visit again, and you should see the page:

Image 8

← Cpp IntroNginx Install Setup β†’