Django templates

Prerequisites

Django template

  • Django template is a text document or a Python string marked-up using the Django template language.
  • Django separates the views and templates for better readability and maintainability
    • views: responsible for handling the request and generating the context for the template
    • templates: templates uses the context generated by the views and creates the HTTP response

Configure template directory

  • Create a directory named templates at project level.
  • The project structure should look like below.
.
├── db.sqlite3
├── manage.py
├── my_app
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── my_project
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── templates
  • open file my_project/settings.py and update the TEMPLATES setting as below.
# .....
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # include template directories here
        'DIRS': ['templates',],
        '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',
            ],
        },
    },
]
# .....

use template in django view

  • Create the template file templates/index.html in the project root directory.
  • Let's use the code from Django first view and modify it as below.

my_app/views.py

from django.shortcuts import render

def first_view(request):
    template = "index.html"
    context = {
        "title": "Introduction",
        "name": "Shiva",
        "profession": "Software Developer",
        "country": "India"
    }
    return render(request, template, context)
  • render is function provided by django which takes the request, template, context and returns the HTTP response.
  • Let's look at the template code.

tempaltes/index.html

<html>
  <head>
    <title>{{ title }}</title>
  </head>
  <body>
    <table>
      <tbody>
        <tr>
          <td>Name</td><td>{{ name }}</td>
        </tr>
        <tr>
          <td>Profession</td><td>{{ profession }}</td>
        </tr>
        <tr>
          <td>Country</td><td>{{ country }}</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

References: