Back to Study Material Python

Django Templates

Django's template language (DTL) is a text-based template system similar to Jinja2 but with deliberate limitations. It was designed to be safe for non-prog...

Django Templates

Rendering Pages with Django Templates

Django's template language (DTL) is a text-based template system similar to Jinja2 but with deliberate limitations. It was designed to be safe for non-programmers to edit, so it intentionally prevents arbitrary Python code execution inside templates.

Django templates use the same three constructs: {{ variable }}, {% tag %}, and {# comment #}.

Rendering a template from a view: from django.shortcuts import render

def product_list(request): products = Product.objects.all() return render(request, 'shop/product_list.html', {'products': products, 'title': 'Our Products'})

Template variables access object attributes and dictionary keys with dot notation: {{ product.name }} {{ product.category.name }} <!-- traverse relationships --> {{ user.get_full_name }} <!-- call no-argument methods -->

Built-in template filters: {{ product.price|floatformat:2 }} <!-- format decimal --> {{ article.body|truncatewords:30 }} <!-- first 30 words --> {{ date_value|date:"D d M Y" }} <!-- "Mon 15 Jan 2024" --> {{ text|linebreaks }} <!-- converts \n to <p> tags --> {{ value|pluralize }} <!-- "item" vs "items" -->

Template tags for control flow: {% for product in products %} <p>{{ forloop.counter }}. {{ product.name }}</p> {% empty %} <p>No products found.</p> {% endfor %}

forloop variables: forloop.counter (1-indexed), forloop.counter0 (0-indexed), forloop.first, forloop.last, forloop.revcounter.

Django template inheritance uses the same extends/block pattern: {% extends 'base.html' %} {% block page_title %}Products{% endblock %} {% block content %} {% include 'partials/breadcrumb.html' %} ... {% endblock %}

The include tag embeds another template. The with tag creates scoped variables: {% with total=order.items.count %} <p>{{ total }} item{{ total|pluralize }} in your order.</p> {% endwith %}

The url tag generates URLs by name, avoiding hardcoded paths: <a href="{% url 'product-detail' product.pk %}">{{ product.name }}</a>

The csrf_token tag inserts a hidden CSRF token in forms: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form>

Practical tip: Use template tags over template filters when you need to pass multiple arguments or perform complex operations. Create custom tags in templatetags/ directories within your app.

Exam tip: Django's template language intentionally blocks calling Python functions with arguments inside templates. This is a design choice, not a bug. Move complex logic into the view or create custom template tags.