Codementor Events

Django Template - How to code dynamic pages in Django

Published Jun 11, 2021Last updated Jun 15, 2021
Django Template - How to code dynamic pages in Django

Hello Coders,

This article is a soft introduction to Django and especially to Django Template System, a powerful engine that helps us to code faster dynamic pages and web apps in general. For newcomers, Django is a popular web framework written in Python that comes with many built-in features and security patterns provided by experienced developers. Topics covered by this article:

  • Set up the environment: Install Python and Django
  • Django cheat-sheet: a short-list with useful commands
  • Django Template Cheat-sheat - list all key features
  • Mention a few open-source samples for curious minds

Django Template - Open-source starter with Pixel Lite Design.


Thanks in advance for your attention. Let's go!


Set up the Environment

Being a Python framework, in order to use Django, we need Python properly installed in our workstation. Most systems (Linux, MacOs) come with Python preinstalled and we can easily check this by opening a terminal window and type python --version. On my M$ Windows the output looks like this:

$ python
Python 3.8.4 (tags/v3.8.4:dfa645a, Jul 13 2020, 16:46:45) ...
Type "help", "copyright", "credits" or "license" for more information.
>>>

In case you're not sure if Python is already installed or the above command returns an error, access the official download page and select the installer that matches your operating system. After the installation is finished, re-check in the terminal if Python is available.

Next Step - Install Django

Once the Python is up & running, we can install Django using PIP, the official package manager:

$ pip install django

The above command will install Django system-wide but we can also isolate the installation using a virtual environment:

$ virtualenv env               # create a virtual environment
$ source env/bin/activate      # activate the environment
$
$ pip install django           # install Django INSIDE the environment 

The difference is the visibility of the Django installation. Once we exit from the virtual environment using the deactivate command, Django is no longer available. This concept is widely used by Python programmers and assures dependency isolation across multiple Python applications. If this concept sounds confusing, please access a comprehensive article that explains in deep the usefulness: Python Virtual Environments.

Check Django Version

$ python                      # invoke Python in the terminal
Python 3.8.4 ... on win32     # command output 
>>> import django             # Import Django library
>>> django.__version__        # Print the current version  
'3.2.4'
>>>

Django Cheat-Sheet

This section contains a summary with a few useful commands we usually type in most Django projects.

Create and activate a virtual environment (Unix based systems)

$ virtualenv env
$ source env/bin/activate

For Windows based systems

$ virtualenv env
$ .\env\Scripts\activate

Install Django - the latest stable version

$  pip install django

Install Django - a specific version

$  pip install django==2.2.10

Create Django Project

$ mkdir django-templates              # create the project directory
$ cd django-templates                 # change the current directory
$ 
$ django-admin startproject config .  # generate the project skeleton
$                                     # NOTE that small `.`

Prepare the database - aka database migration

$ python manage.py makemigrations
$ python manage.py migrate

The migrations should be executed when a new project is created or when we modify the database (add new table, update existing table definition).

Start the project

$ python manage.py runserver # default port 8000

This command starts the project using Django embedded server on port 8000. To start the project on another port, just add an extra argument to the command:

$ python manage.py runserver 1234  # the new port is now 1234

Create a super user - to access the admin section

$ python manage.py createsuperuser

Create a new Django App

$  python manage.py startapp sample_app

This command will create a new Django app called sample_app.

Start the Django Shell

$ python manage.py shell

Select ALL registered users

$ python manage.py shell
>>>
>>> from app_name.models import User
>>> User.objects.all()

Django Template Language

Here is a short list with features offered by the Django template system (the most popular):

  • Inject variables, Lists, classes into templates
  • Filters to transform the information directly in the template in many ways
  • Conditionals (test variable presence or value) {% if %}...{% endif %}
  • Loops (iterate on lists) - {% for x in y %}...{% endfor %}
  • Imports (components reuse) {% include "header.html" %}
  • Inheritance (extend page templates) {% extends "base.html" %}
  • Block Declaration {% block content %}...{% endblock %}

Let's iterate on each item:

Variables and lists

Django template system knows how to render simple variables, class attributes, and even accessing the items of a list by index.

{{ simple_data }}         <-- simple variable
{{ my_address.street }}   <-- address is a class
{{ some_list.1 }}         <-- access list items by index  

Filters - simple helpers useful to transform the information with ease

{{ my_name|upper }}             <-- Uppercase the name
{{ some_discount|default:"0" }} <-- If discount is not provided, value 0 is used
{{ title|truncatechars:20 }}    <-- Truncate the variable to the desired lenght

Conditionals - useful to test a variable presence or value

{% if discount %}

    <span>Special Offer {{ discount }}

{% else %}

    <span>Regular Price {{ price }}

{% endif %}   

Loops - how to iterate on lists

<ul>
    {% for i in my_list %}
        <li>{{ i }}</li>
    {% endfor %}
</ul>

Imports - components reuse

This feature is useful when we code large projects where parts of the UI are common to many pages, like the footer or side menu.

<p>
    Simple text here.
</p>

{% include "includes/footer.html" %} <-- Import directive

The above code chunk imports and reuse the footer component.

Template Inheritance - allows to extend template with specific information

Template inheritance empowers the developer to build a base template that contains the common elements of your site and defines blocks that child templates can override like page title, highlight the active menu and other things specific to the current page.

Master Template Sample - this file will be later reused (extended)

<html>
  <head>
    <title>My Django Template {% block title %}{% endblock %} </title>
  </head>
  <body>
    <div class="container">
      <h2>Master template information</h2>
      <br>
      { block content }{ endblock }
      <br>
    </div>
  </body>
</html>

Child template - that extends the base template

{ extends "base.html" }

{ block title } Child Title { endblock }

{ block content }
  Child content here
{ endblock }

When Django loads child.html, the { extends } block informs the engine to merge the base.html template with the content provided by child.html.

  • { block title } becomes Child Title
  • { block content } becomes Child content here

To make this article more useful, I've coded a simple Django project with a few sample pages related to above topics.


Django Template Sample

This simple Django starter can be donwloaded from Github. Let's build the sample and take a closer look at the configuration and provided pages:

Clone the Code from the repository

$ git clone https://github.com/app-generator/django-templates.git
$ cd django-templates

<br />

Step #2 - Create and activate a virtual environment

$ # Virtualenv modules installation (Unix based systems)
$ virtualenv env
$ source env/bin/activate
$
$ # Virtualenv modules installation (Windows based systems)
$ # virtualenv env
$ # .\env\Scripts\activate

<br />

Step #3 - Install Django

$ pip install django

Project Configuration

The config directory contains at least two relevant files:

  • config/settings.py - global project settings
  • config/urls.py - project routing rules

<br />

Sample_app directory, created with python manage.py startapp will serve the html files from templates directory. According to the product configuration, HTML pages are located in the templates directory.

# Contents of config/settings.py
...
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates")  # <- Specify where the directory is located

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR],                     # <- Informs Django about it
        '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',
            ],
        },
    },
]
...

Template Samples

index.html - showcases a simple file

On access the ROOT of the app or simply index.html a simple file is served from templates directory.

variables.html - Display in the HTML page a simple variable sent by the Django backend

{{ variable }}

lists.html - iterate over a simple list with integers

<h4>The List:</h4>
<ul>
{% for i in list %}
<li>{{ i }}</li>
{% endfor %}
</ul>

Footer Component - a common footer is used by all sample pages

{% include "includes/footer.html" %}

On top of this simple pages, the project comes with three more simple pages styled with Bootstrap5, Bulma and Tailwind.

Django Template - Bootstrap 5 Starter.


Django Template - Bulma CSS Starter.


Django Template - Bulma CSS Starter.


Thanks for reading! For more resources, please access:

Discover and read more posts from Adi Chirilov - Sm0ke
get started