The amount of processing you can do on data within Django templates is intentionally limited. Django’s philosophy is to enforce the separation of presentation and business logic whenever possible. Thus, you can loop through an iterable object, and you can perform if/then/else tests, but modifying the data within a template is discouraged.

For instance, you could encode a simple “if” test this way:


{% if year > 2000 %}
21st century year: {{year}}
{% else %}
Pre-21st century year: {{year}}
{% endif %}

The {% and %} markers delimit blocks of code that can be executed in Django’s template language.

If you want to use a more sophisticated template processing language, you can swap in something like Jinja2 or Mako. Django includes back-end integration for Jinja2, but you can use any template language that returns a string—for instance, by returning that string in an HttpResponse object, as in the case of our “Hello, world!” route.

In versions 6 and up, Django supports template partials, a way to create portions of a template that can be defined once and reused throughout a template. This lets you precompute a given value once over the course of a given template—such as a fancy display version of a user name—and re-use it without having to recompute it each time it’s displayed.

Doing more with Django

What you’ve seen here covers only the most basic elements of a Django application. Django includes a great many other components for use in web projects. Here’s a quick overview:

  • Databases and data models: Django’s built-in ORM lets you define data structures and relationships between them, as well as migration paths between versions of those structures.
  • Forms: Django provides a consistent way for views to supply input forms to a user, retrieve data, normalize the results, and provide consistent error reporting. Django 6 added support for Content Security Policy, a way to prevent submitted forms from being vulnerable to content injection or cross-site scripting (XSS) attacks.
  • Security and utilities: Django includes many built-in functions for caching, logging, session handling, handling static files, and normalizing URLs. It also bundles tools for common security needs like using cryptographic certificates or guarding against cross-site forgery protection or clickjacking.
  • Tasks: Django 6 added a native mechanisms for creating and managing long-running background tasks, without holding up a response to the user. Note that Django only provides ways to set up and keep track of tasks; it doesn’t include the actual execution mechanism. The only included back ends for tasks are for testing, so you will either need to add a third-party solution or write your own using Django’s back-end task code as a base.