Lesson 16 of 60 – Django Templates
27%

Django Templates

Django Templates are HTML files used to create the user interface of a Django website. Templates allow us to display HTML pages and dynamic data sent from Django views.

Note: Django uses its own template language called the Django Template Language (DTL). It allows us to use variables, tags, filters, conditions, and loops inside HTML.

1. What is a Django Template?

A Django template is usually an HTML file that contains the structure of a webpage. It can also contain dynamic Django template code.

<h1>Welcome to My Website</h1>

Templates are used to separate the presentation layer from Python application logic.

2. Why Use Templates?

Django templates provide several benefits:

  • Create HTML pages
  • Display dynamic data
  • Reuse common layouts
  • Use conditions and loops
  • Keep HTML separate from Python logic

3. Creating a Templates Folder

A common approach is to create a templates folder inside a Django app.

myapp/
    views.py
    models.py
    templates/
        home.html

The HTML file can then be rendered from a view.

4. Creating an HTML Template

Create a file named home.html:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>

    <h1>Welcome to Django</h1>

</body>
</html>

5. Rendering a Template

Django provides the render() function to return an HTML template.

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

6. The render() Function

The render() function usually receives the request object and the name of the template.

return render(request, 'home.html')

It creates an HTTP response containing the rendered template.

7. Template Configuration

Django needs to know where templates are located. Template configuration is usually handled in settings.py.

TEMPLATES = [
    {
        'BACKEND':
        'django.template.backends.django.DjangoTemplates',

        'DIRS': [],
        'APP_DIRS': True,
    },
]

8. APP_DIRS

When APP_DIRS is set to True, Django looks for templates inside the templates directory of installed applications.

'APP_DIRS': True

This is a common setup for app-level templates.

9. Template Directory Structure

project/
│
├── manage.py
│
├── myproject/
│
└── myapp/
    ├── views.py
    ├── models.py
    └── templates/
        └── home.html

The template can be rendered from a view in the application.

10. Template Variables

Template variables allow us to display values passed from a view.

<h1>Hello {{ name }}</h1>

Double curly braces {{ }} are used for displaying variables.

11. Passing Data from View

def home(request):

    data = {
        'name': 'Rahul'
    }

    return render(
        request,
        'home.html',
        data
    )

The template can access the name value.

12. Displaying a Variable

View:

def home(request):
    return render(
        request,
        'home.html',
        {'name': 'Amit'}
    )

Template:

<h1>Welcome {{ name }}</h1>

The browser will display the value passed by the view.

13. Multiple Variables

def profile(request):

    data = {
        'name': 'Rahul',
        'age': 21,
        'city': 'Patna'
    }

    return render(
        request,
        'profile.html',
        data
    )

The template can display all these values.

14. Template Dot Notation

Django templates can access attributes or dictionary values using dot notation.

{{ student.name }}
{{ student.age }}
{{ student.email }}

This is useful when displaying object or dictionary data.

15. Django Template Tags

Template tags allow us to perform logic or special operations inside templates.

{% if user %}
    <p>Welcome</p>
{% endif %}

Template tags are written using {% %}.

16. If Condition

{% if age >= 18 %}
    <p>You are an adult.</p>
{% else %}
    <p>You are a minor.</p>
{% endif %}

Django templates support conditional rendering using template tags.

17. For Loop

The for tag can be used to display multiple items.

{% for student in students %}
    <p>{{ student.name }}</p>
{% endfor %}

18. Template Filters

Filters modify or format values before they are displayed.

{{ name|upper }}

The upper filter converts text to uppercase.

{{ name|lower }}

The lower filter converts text to lowercase.

19. Static Files in Templates

CSS, JavaScript, and images are commonly managed as static files in Django.

{% load static %}

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

The static template tag generates the appropriate static file URL.

20. Template Comments

Django provides template comment syntax for comments that should not be rendered.

{# This is a template comment #}

For multi-line comments, Django also provides the comment template tag.

21. Using HTML with Django Templates

A Django template can contain normal HTML together with Django template syntax.

<h1>{{ title }}</h1>

<p>Welcome to our website.</p>

{% if logged_in %}
    <p>You are logged in.</p>
{% endif %}

22. Template and View Relationship

Browser
   ↓
URL
   ↓
View
   ↓
Template
   ↓
HTML Response
   ↓
Browser

The view prepares data and the template is responsible for presenting that data.

23. Passing a List to a Template

View:

def students(request):

    students = [
        'Rahul',
        'Amit',
        'Priya'
    ]

    return render(
        request,
        'students.html',
        {'students': students}
    )

Template:

{% for student in students %}
    <p>{{ student }}</p>
{% endfor %}

24. Template with Database Data

Templates can display records retrieved from a Django model.

def students(request):

    students = Student.objects.all()

    return render(
        request,
        'students.html',
        {'students': students}
    )

The template can loop through the returned records.

25. Using a Base Template

A base template can contain common website elements such as the header, navigation, and footer.

<!DOCTYPE html>
<html>
<body>

<header>My Website</header>

{% block content %}
{% endblock %}

<footer>Copyright</footer>

</body>
</html>

26. Extending a Base Template

Another template can reuse a base template with the extends tag.

{% extends 'base.html' %}

{% block content %}

<h1>Home Page</h1>

{% endblock %}

This helps avoid repeating the same HTML structure.

27. Template Inheritance

Template inheritance allows multiple pages to share a common layout.

  • Create a base template
  • Define content blocks
  • Extend the base template
  • Place page-specific content inside blocks

This makes large websites easier to maintain.

28. Common Template Errors

  • Incorrect template file name
  • Incorrect templates folder location
  • Missing APP_DIRS configuration
  • Incorrect variable name
  • Incorrect template tag syntax
  • Forgetting {% load static %} when needed
  • Incorrect template inheritance

29. Complete Template Example

views.py

from django.shortcuts import render

def home(request):

    data = {
        'title': 'Django Home',
        'name': 'Rahul'
    }

    return render(
        request,
        'home.html',
        data
    )

home.html

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>

<body>

    <h1>Welcome {{ name }}</h1>

</body>
</html>

30. Summary of Django Templates

Django templates provide a powerful way to create dynamic HTML pages. They work together with views to display application data to users.

  • Templates are commonly HTML files.
  • render() is used to return templates.
  • Variables use {{ }}.
  • Template tags use {% %}.
  • Filters modify displayed values.
  • Templates can use conditions and loops.
  • Static files can be loaded using Django's static template tag.
  • Template inheritance helps reuse layouts.
  • Templates can display database information.

📌 Key Points

  • Django templates are mainly used to create the presentation layer.
  • Templates can display dynamic data sent by views.
  • {{ variable }} displays a value.
  • {% tag %} performs template operations.
  • Conditions and loops can be used inside templates.
  • Template filters can format values.
  • render() connects a view with a template.
  • Template inheritance helps create reusable layouts.

🧠 Quick Quiz

Question: Which function is commonly used to render a Django template?