Django Templates: Best Practices

Table of Contents

Introduction to Django templates

Django, as a web framework, uses templates as a way of producing static HTML from the output of a Django view. In practice, Django’s templates are simply HTML files, with some special syntax and a set of tools which lets Django render the HTML page on-the-fly for the visiting user. Templates are highly customizable, but are meant to be simple, with most of the “heavy” logic going into the view. Let’s dive deeper and learn some standard ways of dealing with common problems.

Simple start with Django templates

By default, Django comes with a ton of built-in template tags and filters that help us perform repeatable template tasks throughout our apps. 

Tags: Tags provide arbitrary logic in the rendering process. Django leaves this definition fairly vague, but tags are able to output content, grab content from the database (more on this later), or perform control operations like if statements or for loops.

Examples of tags:

{% firstof user.is_active user.is_staff user.is_deleted %}

The firstof tag will output the first provided variable which evaluates to True. This is a good replacement for a large if/elif/elif/elif/elif block that’s just evaluating on truthiness within your Django templates.

{% for product in product_list %}
    <li>{{ }}: ${{ product.price }}</li>
{% endfor %}

The for tag in Django will loop over each item in a list, making that item (product, in this case) available in the template context before the tag is closed with endfor. This is a widely used pattern when working with lists of Django model instances which have been returned from the view.

Filters: Filters transform the values of variables and arguments. Filters would be used in tasks like rendering a string in uppercase or formatting a date string into a user’s region.

Examples of filters:

{{ value|date:'D d M Y' }}

The date filter will format a date (value, in the example) given a string with some format characters. The example would output the string: Mon 01 Apr 2019.

{{ value|slugify }}

The slugify filter will convert the spaces of a string into hyphens and convert the string to lowercase, among other things. The output of this example would-look-something-like-this.

Back to Top