# Django Template Tags and Filters - Full Text > The complete text of all 31 built-in template tags and 58 built-in template filters. - Content tracks the Django 6.0 documentation. - An index of links is available at https://www.djangotemplatetagsandfilters.com/llms.txt. # Template Tags --- title: '{% autoescape %}' description: turns autoescaping of HTML on or off. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/autoescape/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#autoescape --- # {% autoescape %} turns autoescaping of HTML on or off. ## Documentation When autoescaping is on, which is the default, all HTML tags in variables will be escaped. The following code will turn autoescaping off on a block of content: ```django {% autoescape off %} Variables in this block will not be escaped. {% endautoescape %} ``` #### Arguments The `autoescape` tag takes one argument, which must be either “on” or “off”: - `on` (the default) – The HTML in all variables will be escaped using HTML entities. - `off` – The HTML will not be escaped. As autoescaping is applied by default, you are most likely to use this tag to turn autoescaping off. It is useful, for example, if you are storing HTML in a database (e.g., for a blog article or a product description). #### Variable ```django blurb = '

You are pretty smart!

' ``` #### Template ```django {{ blurb }} ``` #### Result ```django

You are pretty smart!

``` The client (e.g., a browser) would then interpret was returned, so your users would see this HTML in the browser:

You are pretty smart!

The following code, on the other hand, would return *unescaped* HTML to the client: #### Template ```django {% autoescape off %} {{ blurb }} {% endautoescape %} ``` #### Result ```django

You are pretty smart!

``` In this case, your users would see: You are *pretty* smart! > #### Warning: Always Escape User-entered Data > Never trust user-entered data. Only turn autoescaping off if you are sure the content is safe (i.e., you wrote it). ## Commentary **Be careful with this!** Consider the following: #### Variable ```django blurb_dangerous = '' ``` #### Template ```django {% autoescape off %} {{ blurb_dangerous }} {% endautoescape %} ``` #### Result ```django ``` An alternative, and often a better/safer approach, is to use the [`safe` filter](/filters/safe/) on each variable that you want to output without escaping. That method is only safer because it is more obvious which variables are being regarded as safe; however, it still carries with it the risk of a hacker injecting JavaScript into your web pages. See [Wikipedia](https://en.wikipedia.org/wiki/Cross-site_scripting) for more information on Cross-site scripting. --- title: '{% block %}' description: delineates a block of content that can be overwritten in child templates. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/block/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#block --- # {% block %} delineates a block of content that can be overwritten in child templates. ## Documentation Delineates a block of content that can be overwritten in child templates. ## Commentary This is well documented under [Template Inheritance in the official documentation](https://docs.djangoproject.com/en/6.0/ref/templates/language/#template-inheritance). --- title: '{% comment %}' description: used to comment out code. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/comment/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#comment --- # {% comment %} used to comment out code. ## Documentation Used to comment out code to prevent template tags or variables from being interpreted and/or to prevent the content from being delivered to the browser. An optional note can be included in the open comment tag. #### Template ```django {% comment "Should we include this?" %} Created on: {{ joke.created }} Last updated: {{ joke.updated }} {% endcomment %} ``` Note that single lines of text can be commented out using `{#` and `#}`: ```django {# This is a comment. #} ``` --- title: '{% csp_nonce_attr %}' description: renders the CSP nonce attribute on ` ``` #### Result ```django ``` #### Rendering Form Media Pass a `Media` object and the tag renders the whole asset block for you, nonce included: #### Template ```django {% csp_nonce_attr form.media %} ``` #### Result ```django ``` #### Requirements The nonce value comes from the `django.template.context_processors.csp` context processor. In both forms above, if that context processor is not configured, the assets are rendered without a nonce attribute. #### Settings ```django TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "context_processors": [ # ... "django.template.context_processors.csp", ], }, }, ] ``` ## Commentary A nonce-based Content Security Policy is one of the better defenses against cross-site scripting, and until now wiring one up in templates meant reaching for a third-party package like `django-csp` or hand-rolling a context variable. Having it in core is a real win. The `{% csp_nonce_attr form.media %}` form is the one to remember. Form media has always been awkward under CSP because you do not control the markup Django generates for it — you just render `{{ form.media }}` and hope. This tag hands you that same block with nonces attached. **Watch out for the silent failure.** If you forget the `csp()` context processor, this tag does not raise an error — it renders an empty string, and your assets go out with no nonce at all. If your CSP is not enforcing yet, everything will look like it is working. Check the rendered HTML for an actual `nonce` attribute before you trust it. Note this tag handles the *nonce* only. You still need to send the `Content-Security-Policy` header itself, and a nonce in your markup does nothing until that header names it. --- title: '{% csrf_token %}' description: protects against cross site request forgery. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/csrf_token/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#csrf-token --- # {% csrf_token %} protects against cross site request forgery. ## Documentation The `{% csrf_token %}` tag must be included in all Django forms. This will generate a hidden `input` in the form like this: ```django ``` This value will be checked using Django’s built-in middleware to protect against [cross site request forgery](https://docs.djangoproject.com/en/6.0/ref/csrf/). ## Commentary Use it. --- title: '{% cycle %}' description: cycles through list of arguments. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/cycle/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#cycle --- # {% cycle %} cycles through list of arguments. ## Documentation Cycles through list of arguments. #### Variable ```django fruits = ['Apples', 'Bananas', 'Pears', 'Grapes', 'Oranges'] ``` #### Template ```django
    {% for fruit in fruits %}
  1. {{ fruit }}
  2. {% endfor %}
``` #### Result ```django
  1. Apples
  2. Bananas
  3. Pears
  4. Grapes
  5. Oranges
``` ## Commentary The [official documentation](https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#cycle) has some good examples of more advanced usage. --- title: '{% debug %}' description: outputs debugging information. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/debug/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#debug --- # {% debug %} outputs debugging information. ## Documentation Dumps a ton of debugging information including the full `context` and information on the installed packages. ## Commentary We do not find this too useful. --- title: '{% extends %}' description: signals that the template extends a parent template. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/extends/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#extends --- # {% extends %} signals that the template extends a parent template. ## Documentation Signals that the template extends a parent template. ## Commentary This is well documented under [Template Inheritance in the official documentation](https://docs.djangoproject.com/en/6.0/ref/templates/language/#template-inheritance). --- title: '{% filter %}' description: applies a pipe-delimited list of filters to the contained content. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/filter/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#filter --- # {% filter %} applies a pipe-delimited list of filters to the contained content. ## Documentation Applies a pipe-delimited list of filters to the contained content. #### Template ```django {% filter upper|linenumbers|linebreaksbr %}Apple Banana Grape Hamburger Pepper Corn{% endfilter %} ``` #### Result ```django 1. APPLE
2. BANANA
3. GRAPE
4. HAMBURGER
5. PEPPER
6. CORN ``` --- title: '{% firstof %}' description: returns the first argument in a list of arguments that evaluates to `True`. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/firstof/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#firstof --- # {% firstof %} returns the first argument in a list of arguments that evaluates to `True`. ## Documentation Returns the first argument in a list of arguments that evaluates to `True`. #### Variables ```django a = False b = 0 c = "" d = "hello" ``` #### Template ```django {% firstof a b c d %} ``` #### Result ```django hello ``` The tag allows for a default string literal: ```django {% firstof a b c d "goodbye" %} ``` The default string will be used if all of the preceding arguments evaluate to `False`. --- title: '{% for %}' description: for loop. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/for/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#for --- # {% for %} for loop. ## Documentation Often used to loop through querysets, but it can be used to loop through any iterable. #### Looping through a Queryset ```django ``` #### Looping through a Dictionary ```django
    {% for item, remaining in inventory.items %}
  1. {{ item }}: {{ remaining }}
  2. {% endfor %}
``` #### Looping through a List ```django
    {% for fruit in fruits %}
  1. {{ fruit }}
  2. {% endfor %}
``` To loop through a list in reverse order, used `reversed`: #### Looping through a List in Reverse ```django
    {% for fruit in fruits reversed %}
  1. {{ fruit }}
  2. {% endfor %}
``` #### Empty Iterables Sometimes, you won’t be sure that your iterable contains any values. This is especially true with querysets. In such case, you can use the `empty` tag to output a message indicating that no records were found. For example: ```django ``` #### Looping through a List displaying a Counter ```django {% for fruit in fruits %} {% endfor %}
{{ forloop.counter }} {{ fruit }}
``` #### Variables Available in `for` Loops The following variables are available within `for` loops: 1. `forloop.counter` – The current iteration starting with `1`. 2. `forloop.counter0` – The current iteration starting with `0`. 3. `forloop.revcounter` – The iteration’s position from the end. For the last iteration, this will be `1`. 4. `forloop.revcounter0` – The remaining iterations. For the last iteration, this will be `0`. 5. `forloop.first` – `True` for the first iteration. 6. `forloop.last` – `True` for the last iteration. 7. `forloop.length` – The total number of items in the sequence. **New in Django 6.0.** 8. `forloop.parentloop` – The current loop’s parent loop. ## Commentary Also see the [`ifchanged`](/tags/ifchanged/) tag. --- title: '{% for … empty %}' description: display text when for loop is empty. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/for-empty/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#for-empty --- # {% for … empty %} display text when for loop is empty. ## Documentation [See **Empty Iterables** in `for` tag.](/tags/for/#empty-iterables) --- title: '{% if %}' description: if condition. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/if/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#if --- # {% if %} if condition. ## Documentation Conditionals in Django templates work just like they do in Python. The syntax is: ```django {% if some_conditions %} Output this block. {% elif other_conditions %} Output this block. {% else %} Output this block. {% endif %} ``` All of the Python comparison and logical operators are available: #### Comparison Operators - `==` – Equals. - `!=` – Doesn’t equal. - `>` – Is greater than. - `<` – Is less than. - `>=` – Is greater than or equal to. - `<=` – Is less than or equal to. - `is` – Is the same object. - `is not` – Is not the same object. - `in` – Is in a sequence. \*Note that the only types of sequences you can create in the template are lists of strings, which you do by comma-separating the values: ```django {% if animal in "elephant,giraffe,donkey" %} ``` Other sequences must be made available to the template from the view. #### Logical Operators - `and` (e.g., `if a and b:`) - `or` (e.g., `if a or b:`) - `not` (e.g., `if not a:`) ## Commentary 1. You must include spaces around the comparison operators. ```django {% if a == b or c > d %} ``` If you fail to include spaces, you will get a `TemplateSyntaxError`. 2. To check for the existence a URL parameter, use: ```django {% if request.GET.foo %} ``` This will return `True` if `foo` is passed on the querystring and has some value. --- title: '{% ifchanged %}' description: checks if value in loop has changed since last iteration. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/ifchanged/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#ifchanged --- # {% ifchanged %} checks if value in loop has changed since last iteration. ## Documentation Used within a loop to output something if one or more values has changed since the last loop iteration. #### Variable ```django foods = [ {'name': 'Apple', 'category': 'Fruit'}, {'name': 'Banana', 'category': 'Fruit'}, {'name': 'Grape', 'category': 'Fruit'}, {'name': 'Hamburger', 'category': 'Meat'}, {'name': 'Pepper', 'category': 'Vegetable'}, {'name': 'Corn', 'category': 'Vegetable'} ] ``` #### Template ```django {% for food in foods %} {% ifchanged food.category %}

{{ food.category }}

{% endifchanged %}

{{ food.name }}

{% endfor %} ``` #### Result ```django

Fruit

Apple

Banana

Grape

Meat

Hamburger

Vegetable

Pepper

Corn

``` Notice that the `h3` elements only get inserted if the category has changed since the previous iteration. --- title: '{% ifequal %}' description: '**Removed.** Use `{% if a == b %}` instead.' date: '2026-07-31' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/ifequal/ deprecated_in_version: '3.1' doc_link: >- https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#ifequal-and-ifnotequal --- # {% ifequal %} **Removed.** Use `{% if a == b %}` instead. ## Documentation > #### Removed in Django 4.0 > The `ifequal` tag was deprecated in Django 3.1 and **removed in Django 4.0**. > Use `{% if a == b %}` instead. The `ifequal` tag compared two values and displayed the contents of the block if they were equal. #### Old Syntax (No Longer Works) ```django {% ifequal user.username "admin" %} Welcome, admin! {% endifequal %} ``` #### New Syntax ```django {% if user.username == "admin" %} Welcome, admin! {% endif %} ``` ## Commentary This tag no longer exists. Use the [`if`](/tags/if/) tag with the `==` operator instead. --- title: '{% ifnotequal %}' description: '**Removed.** Use `{% if a != b %}` instead.' date: '2026-07-31' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/ifnotequal/ deprecated_in_version: '3.1' doc_link: >- https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#ifequal-and-ifnotequal --- # {% ifnotequal %} **Removed.** Use `{% if a != b %}` instead. ## Documentation > #### Removed in Django 4.0 > The `ifnotequal` tag was deprecated in Django 3.1 and **removed in Django 4.0**. > Use `{% if a != b %}` instead. The `ifnotequal` tag compared two values and displayed the contents of the block if they were not equal. #### Old Syntax (No Longer Works) ```django {% ifnotequal user.username "admin" %} You are not the admin. {% endifnotequal %} ``` #### New Syntax ```django {% if user.username != "admin" %} You are not the admin. {% endif %} ``` ## Commentary This tag no longer exists. Use the [`if`](/tags/if/) tag with the `!=` operator instead. --- title: '{% include %}' description: used to include one template in another. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/include/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#include --- # {% include %} used to include one template in another. ## Documentation Used to include one template in another. #### Parent Template ```django {% block main %}

Content before include

{% include 'asides/book-ad.html' %}

Content after include

{% endblock main %} ``` #### Included Template: `templates/asides/book-ad.html` ```django ``` #### Result ```django

Content before include

Content after include

``` ## Commentary This should not be used to include headers and footers. Use [Template Inheritance](/tags/extends/) for that kind of thing. Use the `include` tag to include asides or callouts that show up on some, but not all pages. #### Pagination Include A great use case for the include tag is pagination, which could go on any `ListView` template. Here is a Bootstrap pagination nav: ```django ``` The resulting nav will look like this: - [« 1…](javascript:alert('just a demo');) - [2](javascript:alert('just a demo');) - 3 - [4](javascript:alert('just a demo');) - […60 »](javascript:alert('just a demo');) --- title: '{% load %}' description: used to load one or more libraries of tags and filters. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/load/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#load --- # {% load %} used to load one or more libraries of tags and filters. ## Documentation Used to load one or more libraries of tags and filters. This could be a library built in to Django, such as [`django.contrib.humanize`](https://docs.djangoproject.com/en/6.0/ref/contrib/humanize), a third-party library, or a library you create yourself. You can only load template tag libraries that are included in `INSTALLED_APPS` in `settings.py`. --- title: '{% lorem %}' description: outputs *lorem ipsum* placeholder text. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/lorem/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#lorem --- # {% lorem %} outputs *lorem ipsum* placeholder text. ## Documentation Outputs [lorem ipsum](https://en.wikipedia.org/wiki/Lorem_ipsum) placeholder text. The tag takes three optional arguments: 1. `count`: The number of *items* (based on the `method`) to output. 2. `method` - `b` – plain-text paragraphs (the default). - `p` – HTML paragraphs. - `w` – words. 3. `random` – When included, outputs random Latin words in place of the traditional *lorem ipsum* text. #### Template ```django {% lorem 2 b %} ``` #### Result ```django Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Atque necessitatibus nemo ducimus, rem quidem fuga possimus architecto molestias voluptatem iste cum quae consequuntur, laudantium hic molestias harum ipsa, sequi quam sapiente deleniti non perspiciatis illo. Hic deserunt laudantium voluptatum ipsum a harum iure labore veritatis consequatur, sunt velit dolorem repellat quas eveniet ducimus asperiores, nesciunt hic at consectetur fugit magni sed, nulla necessitatibus illum accusantium fuga praesentium obcaecati quam voluptatum, aliquam molestias quidem blanditiis ullam optio consectetur? ``` --- #### Template ```django {% lorem 2 p %} ``` #### Result ```django

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Aperiam nostrum reiciendis in, sed hic dignissimos illum incidunt nobis fugiat qui, aliquid doloribus repellat labore possimus inventore soluta consectetur, eius laboriosam animi eaque vitae, quaerat explicabo sed ipsum.

``` --- #### Template ```django {% lorem 10 w %} ``` #### Result ```django lorem ipsum dolor sit amet consectetur adipisicing elit sed do ``` --- #### Template ```django {% lorem 2 b random %} ``` #### Possible Result ```django Sapiente vel ipsum esse cupiditate ut illum, dolor voluptas sed consectetur tenetur nihil, repudiandae commodi obcaecati nobis numquam optio quos quod aperiam reprehenderit, sint modi quae laboriosam maxime culpa deleniti ipsam reprehenderit placeat cum ducimus, quis dicta corporis. Consequatur ratione non id eos inventore tempora soluta eius? At vel eaque, veritatis iusto debitis reprehenderit ducimus exercitationem, laudantium earum impedit ipsum cupiditate aliquam cum natus ipsam rerum rem? A ad impedit placeat error, natus ad possimus commodi velit totam eius reprehenderit consectetur consequatur enim, nulla rerum eius sunt iure iste sed. ``` --- title: '{% now %}' description: outputs the current date and/or time. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/now/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#now --- # {% now %} outputs the current date and/or time. ## Documentation Outputs the current date and/or time. Can be formatted using the same formatting specification as the [`date` filter](/filters/date/). #### Template ```django {% now "SHORT_DATETIME_FORMAT" %} ``` #### Result ```django 04/14/2020 10:42 p.m. ``` --- title: '{% partial %}' description: renders a template fragment defined with `partialdef`. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/partial/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#partial --- # {% partial %} renders a template fragment defined with `partialdef`. ## Documentation Renders a template fragment that was previously defined with the [`partialdef`](/tags/partialdef/) tag. **New in Django 6.0.** #### Arguments - `partial_name` (required) – The name of the template fragment to render. #### Template ```django {# First, define the partial #} {% partialdef button %} {% endpartialdef %} {# Then render it multiple times #} {% with style="primary" label="Save" %} {% partial button %} {% endwith %} {% with style="secondary" label="Cancel" %} {% partial button %} {% endwith %} {% with style="danger" label="Delete" %} {% partial button %} {% endwith %} ``` #### Result ```django ``` #### Using Partials in Loops Partials work well within loops, using the current context for each iteration: #### Template ```django {% partialdef item-row %} {{ item.name }} {{ item.price }} {% endpartialdef %} {% for item in items %} {% partial item-row %} {% endfor %}
``` ## Commentary The `partial` tag works hand-in-hand with [`partialdef`](/tags/partialdef/). Together, they provide a clean way to define and reuse template fragments without creating separate template files. This is especially useful for: - Repeating UI components (buttons, cards, list items) within a single template - Reducing duplication when the same markup appears multiple times - Keeping related template code together instead of splitting into many small files For more details and examples, see the [`partialdef`](/tags/partialdef/) documentation. --- title: '{% partialdef %}' description: defines a reusable template fragment. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/partialdef/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#partialdef --- # {% partialdef %} defines a reusable template fragment. ## Documentation Defines a reusable template fragment that can be rendered multiple times within the same template using the [`partial`](/tags/partial/) tag. This helps avoid repetition and maintain consistent output. **New in Django 6.0.** #### Basic Usage Define a partial with a name, then render it later with the `partial` tag: #### Template ```django {% partialdef user-info %}

{{ user.name }}

{{ user.bio }}

{% endpartialdef %} {# Render the partial elsewhere in the template #} {% partial user-info %} ``` For clarity, you can include the partial name in the closing tag: ```django {% partialdef user-info %} ... {% endpartialdef user-info %} ``` #### Arguments - `partial_name` (required) – A valid template identifier for the fragment. - `inline` (optional) – When included, the partial is both defined and immediately rendered in place. #### Inline Partials Use the `inline` argument to define and immediately render a partial: ```django {% partialdef card inline %}

{{ title }}

{{ content }}

{% endpartialdef %} {# The card is already rendered above, but can be rendered again: #} {% partial card %} ``` #### Direct Access via Template Loading Partials can be accessed directly when loading or including templates using hash syntax: ```django {% include "mytemplate.html#user-info" %} ``` #### Context Partials have access to the current template context. They work within loops and `with` tags, allowing context to be adjusted for each rendering. #### Template ```django {% partialdef button inline %} {% endpartialdef %} {% with style="primary" label="Save" %} {% partial button %} {% endwith %} {% with style="danger" label="Delete" %} {% partial button %} {% endwith %} ``` #### Result ```django ``` ## Commentary Template partials are a welcome addition to Django's template system. They fill a gap between simple variable reuse (with the [`with`](/tags/with/) tag) and full template includes (with the [`include`](/tags/include/) tag). Use partials when you need to repeat a small fragment multiple times within the same template. For fragments that need to be shared across multiple templates, continue using `include`. --- title: '{% querystring %}' description: outputs a URL-encoded query string. date: '2026-07-31' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/querystring/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#querystring --- # {% querystring %} outputs a URL-encoded query string. ## Documentation Outputs a URL-encoded query string based on the provided parameters. The result always includes a leading `?`, making it suitable for direct use in URLs. #### Arguments - **Positional arguments** – Mappings like `QueryDict` or `dict` instances. - **Keyword arguments** – Key-value pairs to add or modify parameters. If no positional arguments are provided, `request.GET` is used as the default source. #### Basic Usage Add or replace parameters in the current query string: #### Template ```django Red, Small ``` #### Result ```django Red, Small ``` #### Modifying the Current Query String When used without positional arguments, it modifies the current `request.GET`: #### Template ```django {# If current URL is ?color=blue&size=M #} Large ``` #### Result ```django Large ``` #### Removing Parameters Pass `None` to remove a parameter: #### Template ```django {# If current URL is ?color=blue&size=M #} Clear color filter ``` #### Result ```django Clear color filter ``` #### Handling Lists If a value is a list, multiple parameters with the same key are output: #### Variable ```django colors = ['red', 'blue'] ``` #### Template ```django Red and Blue ``` #### Result ```django Red and Blue ``` #### Storing in a Variable Use `as` to store the result in a variable: #### Template ```django {% querystring page=page_obj.next_page_number as next_page_url %} Next ``` #### Pagination Example A common use case is pagination links that preserve other query parameters: #### Template ```django {# Preserves filters like ?category=books while changing page #} {% if page_obj.has_previous %} Previous {% endif %} {% if page_obj.has_next %} Next {% endif %} ``` ## Commentary This is a fantastic addition to Django's template tags. Before `querystring`, preserving existing query parameters while modifying one or two was tedious and error-prone. The most common use case is pagination. Previously, you had to manually reconstruct the query string or use a custom template tag. Now it's built in. **Note:** Requires the `django.template.context_processors.request` context processor to be enabled (it is by default in new Django projects). --- title: '{% regroup %}' description: used for outputting list of dictionaries in different orders and structures. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/regroup/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#regroup --- # {% regroup %} used for outputting list of dictionaries in different orders and structures. ## Documentation Used for outputting list of dictionaries in different orders and structures. This is probably the most complex of all the built-in tags, but it is well documented in the [Official Documenation](https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#regroup). --- title: '{% resetcycle %}' description: used to reset a `cycle`. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/resetcycle/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#resetcycle --- # {% resetcycle %} used to reset a `cycle`. ## Documentation Used to reset a `cycle`. This is most useful in nested `for` loops. The name argument is optional and comes in to play when you need to specify which `cycle` you want to restart. ## Commentary The [official documentation](https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#resetcycle) has some good examples of more advanced usage. --- title: '{% spaceless %}' description: removes irrelevant whitespace between HTML tags. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/spaceless/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#spaceless --- # {% spaceless %} removes irrelevant whitespace between HTML tags. ## Documentation Removes irrelevant whitespace between HTML tags. #### Template ```django {% spaceless %}

Created on: {{ joke.created }} Last updated: {{ joke.updated }}

{% endspaceless %} ``` #### Result ```django

Created on: Last updated:

``` Notice that the whitespace within the `small` element has not been removed. Only whitespace between successive opening tags and successive closing tags is removed. --- title: '{% templatetag %}' description: Outputs special characters used to create template tags. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/templatetag/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#templatetag --- # {% templatetag %} Outputs special characters used to create template tags. ## Documentation Outputs special characters used to create template tags (e.g., braces and percentage signs). #### Template ```django {% templatetag openblock %} tag {% templatetag closeblock %} {% templatetag openvariable %} variable {% templatetag closevariable %} {% templatetag openbrace %} braces {% templatetag closebrace %} {% templatetag opencomment %} comment {% templatetag closecomment %} ``` #### Result ```django {% tag %} {{ variable }} { braces } {# comment #} ``` ## Commentary Unless you’re planning to write an online Django tutorial in which you need to output symbols used in Django templates, you’re unlikely to need this tag. --- title: '{% url %}' description: >- used to output the path to the view mapping to `urlname` as defined in the URLConf file. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/url/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#url --- # {% url %} used to output the path to the view mapping to `urlname` as defined in the URLConf file. ## Documentation Used to output the path to the view mapping to `urlname` as defined in the *URLConf* file. ## Commentary This is a big topic. See the official documentation on the [url tag](https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#url) and on [URL dispatcher](https://docs.djangoproject.com/en/6.0/topics/http/urls/). --- title: '{% verbatim %}' description: turn off template rendering. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/verbatim/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#verbatim --- # {% verbatim %} turn off template rendering. ## Documentation Template rendering is turned off between open `{% verbatim blockname %}` and closing `{% endverbatim blockname %}`. #### Template ```django {% verbatim %} {% comment "Should we include this?" %} Created on: {{ joke.created }} Last updated: {{ joke.updated }} {% endcomment %} {% endverbatim %} ``` #### Result ```django {% comment "Should we include this?" %} Created on: {{ joke.created }} Last updated: {{ joke.updated }} {% endcomment %} ``` Notice that the Django template tags are output literally (i.e., *verbatim*). ## Commentary Hard to think of a use case for this. --- title: '{% widthratio %}' description: used to create bar charts and the like. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/widthratio/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#widthratio --- # {% widthratio %} used to create bar charts and the like. ## Documentation Used to create bar charts and the like. The syntax is: ```django {% widthratio this_value max_value max_width %} ``` The value is calculated using this formula: ```django (this_value/max_value) * max_width ``` #### Template ```django
``` #### Result ```django
``` With some CSS applied, the resulting output might look like this: --- title: '{% with %}' description: caches a variable for reuse. date: '2025-12-04' categories: - Template Tag canonical: https://www.djangotemplatetagsandfilters.com/tags/with/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#with --- # {% with %} caches a variable for reuse. ## Documentation Content between an open `with` tag (e.g., `{% with var1=value2 var2=value2… %}`) and close `endwith` tag (e.g., `{% endwidth %}`) have access to the variables defined in the open `with` tag. The `with` tag is useful for reusing the results of an expensive method. Consider the following template: ```django {{ jokes.count }} joke{{ jokes.count|pluralize }} that match your search. ``` In the preceding code, `jokes.count` has to be evaluated twice. The following code assigns `jokes.count` to `joke_count` and then uses the result within the block: ```django {% with joke_count=jokes.count %} { joke_count }} joke{{ joke_count|pluralize }} that match your search. {% endwith %} ``` ## Commentary #### Django tags cannot span multiple lines. It might be tempting to write an open `with` tag like this: **Bad code:** ```django {% with var1 = 'very long value' var2 = 'very long value' var3 = 'very long value' %} ``` But Django will not recognize that as a tag and thus will be surprised by the `endwith` tag. You will end up with an error like this one: ```django Invalid block tag on line 37: 'endwith'. Did you forget to register or load this tag? ``` # Template Filters --- title: '|add' description: adds `arg` to the value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/add/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#add --- # |add adds `arg` to the value. ## Documentation Adds `arg` to the value. This can be used for adding numbers or concatenating strings. #### Variables ```django age = 30 name = 'Nat' ``` #### Template ```django {{ name|'haniel' }} is {{ age|add:20 }}. ``` #### Result ```django Nathaniel is 50. ``` ## Commentary The `add` filter can be used to coerce a string in to an integer in a template. Consider the following: ```django ``` Because `order` is passed on the querystring, it will be a string, but `forloop.counter0` will be an integer, so the two will never be equal. Coercing `request.GET.order` to an integer using `add` solves the problem. An alternative would be to coerce `forloop.counter0` in to a string using the [`slugify` filter as shown here](/filters/slugify/). --- title: '|addslashes' description: adds backslashes before quotation marks to escape them. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/addslashes/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#addslashes --- # |addslashes adds backslashes before quotation marks to escape them. ## Documentation Adds backslashes before quotation marks to escape them. #### Variable ```django blurb = "Where'd you get the coconuts?" ``` #### Template ```django {{ blurb|addslashes }} ``` #### Result ```django Where\'d you get the coconuts? ``` This is particularly useful when you need to include Django variables within JavaScript code. Consider the following: #### Template ```django ``` #### Result ```django ``` This will result in a JavaScript bug as the apostrophe in `Where'd` will close the JavaScript string. Using `addslashes` will fix that: ```django ``` #### Result ```django ``` Notice that the apostrophe in `Where'd` is now escaped. ## Commentary If you are writing raw SQL queries, do **not** use `addslashes` to escape single quotes. Use [parameters](https://docs.djangoproject.com/en/6.0/topics/db/sql/#passing-parameters-into-raw) instead. --- title: '|capfirst' description: capitalizes the first letter of a value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/capfirst/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#capfirst --- # |capfirst capitalizes the first letter of a value. ## Documentation Capitalizes the first letter of a value. #### Variable ```django greeting = 'hello, world!' ``` #### Template ```django {{ greeting|capfirst }} ``` #### Result ```django Hello, world! ``` ## Commentary In general, we prefer using CSS to formatting filters like this one; however, there is no CSS property equivalent to the `capfirst` filter. CSS's `text-transform: capitalize` property works like the [`title`](/filters/title/) filter (i.e., it capitalizes the first letter of each word). Also, there is an advantage to using Django: because the formatting is applied server-side, the value returned to the client will already be formatted appropriately. If the client does not support CSS or has CSS turned off, that will not affect the formatting. And, of course, if you are using Django to output plain text or some other non-HTML format, formatting filters could come in handy. --- title: '|center' description: centers a value within text of `n` characters date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/center/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#center --- # |center centers a value within text of `n` characters ## Documentation Alignment filters add whitespace on one or both sides of the value. #### Variable ```django company = 'Webucator' ``` #### Template ```django {{ "company|center:20" }} ``` #### Result ```django " Webucator " ``` In a browser, whitespace is condensed, so the output would be: " Webucator " ## Commentary As whitespace is condensed by default in HTML pages, alignment filters wouldn’t affect the output unless the text is within a `pre` element or CSS is used to prevent whitespace from being condensed. However, Django can be used to create non-HTML documents as well. In such documents, formatting with whitespace might make more sense. --- title: '|cut' description: removes all instances of `string_to_cut` from the value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/cut/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#cut --- # |cut removes all instances of `string_to_cut` from the value. ## Documentation Removes all instances of the argument string from the value. #### Variable ```django sentence = 'Let’s eat, grandpa!' ``` #### Template ```django {{ sentence|cut:',' } ``` #### Result ```django Let’s eat grandpa! ``` ## Commentary It is hard to think of a good use case for this. --- title: '|date' description: for formatting dates. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/date/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#date --- # |date for formatting dates. ## Documentation Used to format the date and time of a `datetime` or `date` object. The `format` argument can be constructed using [format strings](https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#std:templatefilter-date) or one of the following predefined formats: 1. `DATE_FORMAT` 2. `DATETIME_FORMAT` 3. `SHORT_DATE_FORMAT` 4. `SHORT_DATETIME_FORMAT` #### Variable ```django moon_landing = datetime.datetime(year=1969, month=7, day=21, hour=2, minute=56, second=15, tzinfo=datetime.timezone.utc) ``` #### Sample Formats - `{{ moon_landing }}` – July 21, 1969, 2:56 a.m. - `{{ moon_landing|date }}` – July 21, 1969 - `{{ moon_landing|date:'l, F j, Y' }}` – Monday, July 21, 1969 - `{{ moon_landing|date:"DATE_FORMAT" }}` – July 21, 1969 - `{{ moon_landing|date:"DATETIME_FORMAT" }}` – July 21, 1969, 2:56 a.m. - `{{ moon_landing|date:"SHORT_DATE_FORMAT" }}` – 07/21/1969 - `{{ moon_landing|date:"SHORT_DATETIME_FORMAT" }}` – 07/21/1969 2:56 a.m. Note that the predefined formats are based on the current locale. --- title: '|default' description: used to provide a default string when the variable evaluates to `False`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/default/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#default --- # |default used to provide a default string when the variable evaluates to `False`. ## Documentation Used to provide a default string when the variable evaluates to `False`. #### Variable ```django inventory = { 'gloves': 0, 'hats': 51, 'scarves': 2, 'socks': 13 } ``` #### Template ```django
    {% for item, remaining in inventory.items %}
  1. {{ item }}: {{ remaining|default:"out of stock" }}
  2. {% endfor %}
``` #### Result ```django
  1. gloves: out of stock
  2. hats: 51
  3. scarves: 2
  4. socks: 13
``` --- title: '|default_if_none' description: outputs `default` if and only if the value is `None`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/default_if_none/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#default-if-none --- # |default_if_none outputs `default` if and only if the value is `None`. ## Documentation Outputs `default` if and only if the value is `None`. #### Variables ```django a = None b = 0 c = '' d = False e = [] ``` #### Template ```django
  1. {{ a|default_if_none:"No a" }}
  2. {{ b|default_if_none:"No b" }}
  3. {{ c|default_if_none:"No c" }}
  4. {{ d|default_if_none:"No d" }}
  5. {{ e|default_if_none:"No e" }}
``` #### Result ```django
  1. No a
  2. 0
  3. False
  4. []
``` Notice that the default is only used for `a`. While all the rest evaluate to `False`, they are not `None`. --- title: '|dictsort' description: sorts a list of dictionaries by `key`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/dictsort/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#dictsort --- # |dictsort sorts a list of dictionaries by `key`. ## Documentation Sorts a list of dictionaries by `key`. #### Variable ```django foods = [ {'name': 'Apple', 'category': 'Fruit'}, {'name': 'Banana', 'category': 'Fruit'}, {'name': 'Corn', 'category': 'Vegetable'}, {'name': 'Grape', 'category': 'Fruit'}, {'name': 'Hamburger', 'category': 'Meat'}, {'name': 'Pepper', 'category': 'Vegetable'}, ] ``` #### Template ```django
    {% for food in foods|dictsort:'category' %}
  1. {{ food.name }}, {{ food.category }}
  2. {% endfor %}
``` #### Result ```django
  1. Apple, Fruit
  2. Banana, Fruit
  3. Grape, Fruit
  4. Hamburger, Meat
  5. Corn, Vegetable
  6. Pepper, Vegetable
``` Notice that the list is sorted by category. `dictsort` can also be used to sort lists of other sequences using the index of the item you wish to sort by as the argument. See also: [dictsortreversed](/filters/dictsortreversed). --- title: '|dictsortreversed' description: reverse sorts a list of dictionaries by `key`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/dictsortreversed/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#dictsortreversed --- # |dictsortreversed reverse sorts a list of dictionaries by `key`. ## Documentation Reverse sorts a list of dictionaries by `key`. #### Variable ```django foods = [ {'name': 'Apple', 'category': 'Fruit'}, {'name': 'Banana', 'category': 'Fruit'}, {'name': 'Corn', 'category': 'Vegetable'}, {'name': 'Grape', 'category': 'Fruit'}, {'name': 'Hamburger', 'category': 'Meat'}, {'name': 'Pepper', 'category': 'Vegetable'}, ] ``` #### Template ```django
    {% for food in foods|dictsortreversed:'category' %}
  1. {{ food.name }}, {{ food.category }}
  2. {% endfor %}
``` #### Result ```django
  1. Corn, Vegetable
  2. Pepper, Vegetable
  3. Hamburger, Meat
  4. Apple, Fruit
  5. Banana, Fruit
  6. Grape, Fruit
``` Notice that the list is sorted by category in reverse order. `dictsortreversed` can also be used to sort lists of other sequences using the index of the item you wish to sort by as the argument. See also: [dictsort](/filters/dictsort). --- title: '|divisibleby' description: returns `True` if the value is divisible by `n`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/divisibleby/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#divisibleby --- # |divisibleby returns `True` if the value is divisible by `n`. ## Documentation Returns `True` if the value is divisible by `n`, and `False` otherwise. #### Variable ```django age = 33 ``` #### Template ```django {{ age|divisibleby:2 }} {{ age|divisibleby:3 }} ``` #### Result ```django False True ``` ## Commentary This Django template filter is similar to mod / modulus. It is useful for creating columns when using Bootstrap or some similar library. #### Example Code: ```django
{% for item in items %}
{{ item }}
{% if forloop.counter|divisibleby:3 %} {# Start new row #}
{% endif %} {% endfor %}
``` --- title: '|escape' description: escapes HTML characters. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/escape/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#escape --- # |escape escapes HTML characters. ## Documentation Escapes HTML characters. #### Variable ```django blurb = '

You are pretty smart!

' ``` #### Template ```django {% autoescape off %} {{ blurb|escape }} will output: {{ blurb }} {% endautoescape %} ``` #### Result ```django

You are pretty smart!

will output:

You are pretty smart!

``` The browser output would be: `

You are pretty smart!

` will output: You are *pretty* smart! > The `escape` filter is only relevant if [autoescaping is off](/tags/autoescape/). --- title: '|escapejs' description: escapes characters used in JavaScript strings. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/escapejs/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#escapejs --- # |escapejs escapes characters used in JavaScript strings. ## Documentation Escapes characters used in JavaScript strings. Use [json\_script](/filters/json_script/) instead. > #### Warning > Do not use this filter. It is not safe. > See Adam Johnson’s [Safely Including Data for JavaScript in a Django Template](https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/) for a detailed explanation of how to safely include dynamic data for JavaScript processing. --- title: '|escapeseq' description: applies the `escape` filter to each element of a sequence. date: '2026-07-31' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/escapeseq/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#escapeseq --- # |escapeseq applies the `escape` filter to each element of a sequence. ## Documentation Applies the [`escape`](/filters/escape/) filter to each element of a sequence. #### Variable ```django items = [ '', 'bold', 'plain text' ] ``` #### Template ```django {{ items|escapeseq|join:", " }} ``` #### Result ```django , bold, plain text ``` Each element in the sequence has its HTML characters escaped before being joined. #### Use Case This is useful when you need to join a list of items that may contain HTML, and you want to ensure each item is escaped before joining: ```django {{ user_comments|escapeseq|join:"
" }} ``` Without `escapeseq`, you would need to loop through the items manually to escape each one. ## Commentary This filter complements [`safeseq`](/filters/safeseq/), which does the opposite (marks each element as safe). Use `escapeseq` when you have a sequence of potentially unsafe strings that you need to escape before joining or further processing. See also: [`escape`](/filters/escape/), [`safeseq`](/filters/safeseq/). --- title: '|filesizeformat' description: converts a value in bytes to a friendly file size format. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/filesizeformat/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#filesizeformat --- # |filesizeformat converts a value in bytes to a friendly file size format. ## Documentation Converts a value in bytes to a friendly file size format. #### Variable ```django files = [ { 'filename': 'macOS 64-bit installer', 'filesize': 29163525 }, { 'filename': 'Windows x86-64 executable installer', 'filesize': 26797616 }, { 'filename': 'Windows x86-64 web-based installer', 'filesize': 1348896 } ] ``` #### Template ```django
    {% for file in files %}
  1. {{ file.filename }} ({{ file.filesize|filesizeformat }})
  2. {% endfor %}
``` #### Result ```django
  1. macOS 64-bit installer (27.8 MB)
  2. Windows x86-64 executable installer (25.6 MB)
  3. Windows x86-64 web-based installer (1.3 MB)
``` ## Commentary Useful when outputting the file size of a downloadable file. --- title: '|first' description: outputs the first element in a sequence. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/first/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#first --- # |first outputs the first element in a sequence. ## Documentation Outputs the first element in a sequence. #### Variable ```django veggies = ['Tomatoes', 'Cucumbers', 'Peas'] ``` #### Template ```django {{ veggies|first }} ``` #### Result ```django Tomatoes ``` --- title: '|floatformat' description: rounds a float to `n` decimal places. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/floatformat/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#floatformat --- # |floatformat rounds a float to `n` decimal places. ## Documentation The `floatformat` filter takes an `n` argument for the number of decimal places to round to. Without that argument, it will round to one decimal place unless the decimal value is `0`, in which case it will just output the integer. | filter | 1000.0 | 1000.11 | 3.14159 | | --- | --- | --- | --- | | `{{ i|floatformat }}` | 1000 | 1000.1 | 3.1 | | `{{ i|floatformat:2 }}` | 1000.00 | 1000.11 | 3.14 | | `{{ i|floatformat:0 }}` | 1000 | 1000 | 3 | --- title: '|force_escape' description: Almost identical to `escape`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/force_escape/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#force-escape --- # |force_escape Almost identical to `escape`. ## Documentation Almost identical to `escape`, and you almost definitely want to use `escape` instead. #### Variable ```django shopping_list = '''Carrots Honey Milk Butter''' ``` #### Template with `force_escape` ```django {% autoescape off %} {{ shopping_list|linebreaks|force_escape }} {% endautoescape %} ``` #### Result ```django

Carrots
Honey
Milk
Butter

``` #### Template with `escape` ```django {% autoescape off %} {{ shopping_list|linebreaks|escape }} {% endautoescape %} ``` #### Result with `escape` ```django

Carrots
Honey
Milk
Butter

``` Notice that the `
` tags that are generated with the [`linebreaks`](/filters/linebreaks/) filter are escaped when `force_escape` is used, but not when `escape` is used. ## Commentary You are very unlikely to need this. --- title: '|get_digit' description: returns the digit `i` characters from the right side of the value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/get_digit/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#get-digit --- # |get_digit returns the digit `i` characters from the right side of the value. ## Documentation Returns the digit `i` characters from the right side of a value, which must be an integer. #### Variable ```django num = 6789 ``` #### Template ```django {{ num|get_digit:1 }}, {{ num|get_digit:2 }}, {{ num|get_digit:3 }}, {{ num|get_digit:4 }} ``` #### Result ```django 9, 8, 7, 6 ``` ## Commentary It is hard to think of a use case for this one. --- title: '|iriencode' description: converts an IRI to a string that can be used in a URL. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/iriencode/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#iriencode --- # |iriencode converts an IRI to a string that can be used in a URL. ## Documentation Converts an IRI ([Internationalized Resource Identifier](https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier)) to a string that can be used in a URL. ## Commentary We really don’t know enough about this to comment. --- title: '|join' description: joins a list on `s`. Works just like Python’s `s.join(value)`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/join/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#join --- # |join joins a list on `s`. Works just like Python’s `s.join(value)`. ## Documentation Joins a list on `s`. Works just like Python’s `s.join(value)`. #### Variable ```django veggies = ['Tomatoes', 'Cucumbers', 'Peas'] ``` #### Template ```django {{ veggies|join:', ' }} ``` #### Result ```django Tomatoes, Cucumbers, Peas ``` --- title: '|json_script' description: outputs a Python object as JSON inside of a `script` element. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/json_script/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#json-script --- # |json_script outputs a Python object as JSON inside of a `script` element. ## Documentation Outputs a Python object as JSON inside of a `script` element. This is the safest way to include data to be used by JavaScript. #### Variable ```django classes = { 'Python': [ 'Intro Python', 'Advanced Python', 'Data Science', 'Django' ], 'Databases': [ 'Intro PostgreSQL', 'Intro MySQL', 'Intro SQL Server', 'Intro Oracle' ], 'Web': [ 'HTML', 'CSS', 'JavaScript' ], 'XML': [ 'Intro XML' ] } ``` #### Template ```django {{ classes|json_script:'classdata' }} ``` #### Result ```django ``` You can then use another `script` element to consume this content: ```django
``` You could (and probably should) point to an external JavaScript file rather than using embedded JavaScript. ## Commentary See Adam Johnson’s [Safely Including Data for JavaScript in a Django Template](https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/) for a detailed explanation of how to safely include dynamic data for JavaScript processing. --- title: '|last' description: outputs the last element in a sequence. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/last/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#last --- # |last outputs the last element in a sequence. ## Documentation Outputs the last element in a sequence. #### Variable ```django veggies = ['Tomatoes', 'Cucumbers', 'Peas'] ``` #### Template ```django {{ veggies|last }} ``` #### Result ```django Peas ``` --- title: '|length' description: returns the length of a value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/length/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#length --- # |length returns the length of a value. ## Documentation Returns the length of a value, which can be a string or a sequence. #### Variable ```django classes = { 'Python': [ 'Intro Python', 'Advanced Python', 'Data Science', 'Django' ], 'Databases': [ 'Intro PostgreSQL', 'Intro MySQL', 'Intro SQL Server', 'Intro Oracle' ], 'Web': [ 'HTML', 'CSS', 'JavaScript' ], 'XML': [ 'Intro XML' ] } ``` #### Template ```django
    {% for category, titles in classes.items %}
  1. {{ category }}: {{ titles|length }} class{{ titles|pluralize:"es" }}
  2. {% endfor %}
``` #### Result ```django
  1. Python: 4 classes
  2. Databases: 4 classes
  3. Web: 3 classes
  4. XML: 1 class
``` --- title: '|length_is' description: '**Deprecated.** Use `length` with comparison instead.' date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/length_is/ deprecated_in_version: '4.2' doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#length-is --- # |length_is **Deprecated.** Use `length` with comparison instead. ## Documentation > #### Deprecated in Django 4.2 > The `length_is` filter is deprecated. Use the [`length`](/filters/length/) filter with a comparison operator instead: > ```django > {% if value|length == 3 %}...{% endif %} > ``` Returns `True` if the length of the value is `n`. Otherwise, it returns `False`. This is most useful in a condition. #### Variable ```django veggies = ['Tomatoes', 'Cucumbers', 'Peas'] ``` #### Template ```django {% if veggies|length_is:3 %}

Looks like a trio of veggies tonight!

{% endif %} ``` #### Result ```django

Looks like a trio of veggies tonight!

``` ## Commentary Maybe we are missing something, isn't using the [`length`](/filters/length/) filter just as easy? ```django {% if veggies|length == 3 %}

Looks like a trio of veggies tonight!

{% endif %} ``` --- title: '|linebreaks' description: converts newlines to `
` and `

` tags. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/linebreaks/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#linebreaks --- # |linebreaks converts newlines to `
` and `

` tags. ## Documentation Replaces single newline characters with `
` tags and wraps lines of text separated by two newline characters in `

` tags. #### Variable ```django poem = '''Much to his Mum and Dad’s dismay, Horace ate himself one day. He didn’t stop to say his grace, He just sat down and ate his face. “We can’t have this!” His Dad declared, “If that lad’s ate, he should be shared.”''' ``` #### Template ```django {{ poem|linebreaks }} ``` #### Result ```django

Much to his Mum and Dad’s dismay,
Horace ate himself one day.

He didn’t stop to say his grace,
He just sat down and ate his face.

“We can’t have this!” His Dad declared,
“If that lad’s ate, he should be shared.”

``` --- title: '|linebreaksbr' description: converts all newline characters in `value` to `
` tags. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/linebreaksbr/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#linebreaksbr --- # |linebreaksbr converts all newline characters in `value` to `
` tags. ## Documentation Replaces all newline characters with `
` tags. #### Variable ```django poem = '''Much to his Mum and Dad’s dismay, Horace ate himself one day. He didn’t stop to say his grace, He just sat down and ate his face. “We can’t have this!” His Dad declared, “If that lad’s ate, he should be shared.”''' ``` #### Template ```django {{ poem|linebreaksbr }} ``` #### Result ```django Much to his Mum and Dad's dismay,
Horace ate himself one day.

He didn't stop to say his grace,
He just sat down and ate his face.

"We can't have this!" His Dad declared,
"If that lad's ate, he should be shared." ``` --- title: '|linenumbers' description: prepends each line of text with a line number. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/linenumbers/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#linenumbers --- # |linenumbers prepends each line of text with a line number. ## Documentation Prepends each line of text with a line number. #### Variable ```django shopping_list = '''Carrots Honey Milk Butter''' ``` #### Template ```django {{ shopping_list|linenumbers }} ``` #### Result ```django 1. Carrots 2. Honey 3. Milk 4. Butter ``` In a browser, whitespace is condensed, so the output would be: 1. Carrots 2. Honey 3. Milk 4. Butter ## Commentary Useful for plain text, but not typically for HTML. --- title: '|ljust' description: left justifies a value within text of `n` characters date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/ljust/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#ljust --- # |ljust left justifies a value within text of `n` characters ## Documentation Left justifies a value by padding it with whitespace on the right. #### Variable ```django company = 'Webucator' ``` #### Template ```django {{ "company|ljust:20" }} ``` #### Result ```django "Webucator " ``` In a browser, whitespace is condensed, so the output would be: "Webucator " ## Commentary As whitespace is condensed by default in HTML pages, alignment filters will not affect the output unless the text is within a `pre` element or CSS is used to prevent whitespace from being condensed. However, Django can be used to create non-HTML documents as well. In such documents, formatting with whitespace might make more sense. --- title: '|lower' description: converts a string to lowercase. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/lower/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#lower --- # |lower converts a string to lowercase. ## Documentation Converts an entire string to lowercase. #### Variable ```django greeting = 'HELLO, WORLD!' ``` #### Template ```django {{ greeting|lower }} ``` #### Result ```django hello, world! ``` ## Commentary For web pages, formatting tags like this are not too useful. We prefer using CSS's `text-transform: lowercase` property. However, there is an advantage to using Django: because the formatting is applied server-side, the value returned to the client will already be formatted appropriately. If the client does not support CSS or has CSS turned off, that will not affect the formatting. And, of course, if you are using Django to output plain text or some other non-HTML format, formatting filters could come in handy. --- title: '|make_list' description: converts the value to a list of characters. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/make_list/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#make-list --- # |make_list converts the value to a list of characters. ## Documentation Converts the value to a list of characters. Non-string values are first converted to strings. #### Variables ```django company = 'Webucator' number = 123456789 ``` #### Template ```django {{ company|make_list }}
{{ 123456789|make_list }} ``` #### Result ```django ['W', 'e', 'b', 'u', 'c', 'a', 't', 'o', 'r']
['1', '2', '3', '4', '5', '6', '7', '8', '9'] ``` ## Commentary We cannot think of a single practical use case for this. Can you? --- title: '|phone2numeric' description: converts letters to numbers for a phone number. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/phone2numeric/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#phone2numeric --- # |phone2numeric converts letters to numbers for a phone number. ## Documentation Converts letters to numbers for a phone number. #### Variable ```django tel = '877-WEBUCAT' ``` #### Template ```django {{ tel|phone2numeric }} ``` #### Result ```django 877-9328228 ``` ## Commentary A bit gimmicky, but OK. --- title: '|pluralize' description: returns a pluralization suffix. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/pluralize/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#pluralize --- # |pluralize returns a pluralization suffix. ## Documentation If the value is not 1, '1', or an object of length 1, the `pluralize` filter outputs an “s” or the value of the `suffix` argument if one is used. #### Variable ```django classes = { 'Python': [ 'Intro Python', 'Advanced Python', 'Data Science', 'Django' ], 'Databases': [ 'Intro PostgreSQL', 'Intro MySQL', 'Intro SQL Server', 'Intro Oracle' ], 'Web': [ 'HTML', 'CSS', 'JavaScript' ], 'XML': [ 'Intro XML' ] } ``` #### Template ```django
    {% for category, titles in classes.items %}
  1. {{ category }}: {{ titles|length }} class{{ titles|pluralize:"es" }}
  2. {% endfor %}
``` #### Result ```django
  1. Python: 4 classes
  2. Databases: 4 classes
  3. Web: 3 classes
  4. XML: 1 class
``` ## Commentary Super useful. Much easier and cleaner than using conditional expressions to decide when to pluralize a word. --- title: '|pprint' description: Pretty prints a Python object. Used for debugging. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/pprint/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#pprint --- # |pprint Pretty prints a Python object. Used for debugging. ## Documentation Pretty prints a Python object using [`pprint.pprint`](https://docs.python.org/3/library/pprint.html#pprint.pprint) wrapper. #### Variable ```django context['classes'] = { 'Python': [ 'Introduction to Python Training', 'Advanced Python Training', 'Data Science Training', 'Django Training' ], 'Databases': [ 'Introduction to PostgreSQL Training', 'Introduction to MySQL Training', 'Introduction to SQL Server Training', 'Introduction to Oracle Training' ], 'Web': [ 'HTML Training', 'CSS Training', 'JavaScript Training' ], 'XML': [ 'Introduction to XML Training' ] } ``` #### Template ```django
{{ classes|pprint }}
``` #### Result ```django {'Databases': ['Introduction to PostgreSQL Training', 'Introduction to MySQL Training', 'Introduction to SQL Server Training', 'Introduction to Oracle Training'], 'Python': ['Introduction to Python Training', 'Advanced Python Training', 'Data Science Training', 'Django Training'], 'Web': ['HTML Training', 'CSS Training', 'JavaScript Training'], 'XML': ['Introduction to XML Training']} ``` ## Commentary Could be useful for debugging, though you can do the same thing at the console. --- title: '|random' description: outputs a random item from a sequence. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/random/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#random --- # |random outputs a random item from a sequence. ## Documentation Outputs a random item from a sequence. Like Python’s `random.choice(value)`. #### Variable ```django roshambo = ['Rock', 'Paper', 'Scissors'] ``` #### Template ```django {{ roshambo|random }} ``` #### Possible Result ```django Scissors ``` --- title: '|rjust' description: right justifies a value within text of `n` characters date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/rjust/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#rjust --- # |rjust right justifies a value within text of `n` characters ## Documentation Right justifies a value by padding it with whitespace on the left. #### Variable ```django company = 'Webucator' ``` #### Template ```django {{ "company|rjust:20" }} ``` #### Result ```django " Webucator" ``` In a browser, whitespace is condensed, so the output would be: " Webucator" ## Commentary As whitespace is condensed by default in HTML pages, alignment filters will not affect the output unless the text is within a `pre` element or CSS is used to prevent whitespace from being condensed. However, Django can be used to create non-HTML documents as well. In such documents, formatting with whitespace might make more sense. --- title: '|safe' description: >- indicates that the value is known to be safe and therefore does not need to be escaped. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/safe/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#safe --- # |safe indicates that the value is known to be safe and therefore does not need to be escaped. ## Documentation The `safe` filter indicates that the value is known to be safe and therefore does not need to be escaped. For example, given the following: ```django blurb = '

You are pretty smart!

' ``` This would return *unescaped* HTML to the client: ```django {{ blurb|safe }} ``` #### Result ```django

You are pretty smart!

``` The client (e.g., a browser) would then interpret was returned, so your users would see this HTML in the browser: You are *pretty* smart! > #### Warning 1: Not for JavaScript > The `safe` filter is **not** to be used for escaping JavaScript code. > See Adam Johnson’s [Safely Including Data for JavaScript in a Django Template](https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/) for details. > #### Warning 2: Not for User-entered Data > Never trust user-entered data. Only use this if you are sure the content is safe (i.e., you wrote it). ## Commentary In most cases, we recommend using this filter instead of the [`autoescape`](/tags/autoescape/) tag, because it is specific to a variable and less likely to result in unintended (and potentially dangerous) output. However, you must be careful with the `safe` filter as well. Consider the following: #### Variable ```django blurb_dangerous = '' ``` #### Template ```django {{ blurb_dangerous|safe }} ``` #### Result ```django ``` See the commentary on the [`autoescape`](/tags/autoescape/) tag for more details. --- title: '|safeseq' description: applies the `safe` filter to each element of a sequence. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/safeseq/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#safeseq --- # |safeseq applies the `safe` filter to each element of a sequence. ## Documentation Applies the [`safe`](/filters/safe/) filter to each element of a sequence. #### Variable ```django poem_lines = [ 'Much to his Mum and Dad’s dismay,', 'Horace ate himself one day.', 'He didn’t stop to say his grace,', 'He just sat down and ate his face.', '“We can’t have this!” His Dad declared,', '“If that lad’s ate, he should be shared.”' ] ``` #### Template ```django {{ poem_lines|safeseq|join:'
' }} ``` #### Result ```django Much to his Mum and Dad’s dismay,
Horace ate himself one day.
He didn’t stop to say his grace,
He just sat down and ate his face.
“We can’t have this!” His Dad declared,
“If that lad’s ate, he should be shared.” ``` And the output to the browser looks like this: Much to his Mum and Dad’s *dismay*, Horace **ate himself** one day. He *didn’t stop* to say his grace, He just sat down and **ate his face**. *“We can’t have this!”* His Dad declared, “If that lad’s ate, **he should be shared**.” --- title: '|slice' description: returns a slice of a sequence. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/slice/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#slice --- # |slice returns a slice of a sequence. ## Documentation Returns a slice of a sequence. #### Variable ```django company = 'Webucator' ``` #### Template ```django {{ company|slice:'4:7' }} ``` #### Result ```django cat ``` ## Commentary This is extremely useful for outputting subsets of querysets in a Django template. For example, if you only want to show the first three results of your queryset and hide the rest under a “Show More” link, you use two loops with slicing: ```django
    {% for color in widget.colors|slice:':3' %}
  1. {{ color }}
  2. {% endfor %} {% for color in widget.colors|slice:'3:' %}
  3. {{ color }}
  4. {% endfor %}
``` --- title: '|slugify' description: converts a string to a slug. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/slugify/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#slugify --- # |slugify converts a string to a slug. ## Documentation Converts a string to a slug, for use in a URL. Specifically, it: 1. Converts to lowercase ASCII. 2. Converts spaces to hyphens. 3. Removes all characters except letters, numbers, underscores, and hyphens. 4. Strips leading and trailing whitespace. #### Variable ```django blurb_text = 'Aren’t you a smart one?' ``` #### Template ```django {{ blurb_text|slugify }} ``` #### Result ```django arent-you-a-smart-one ``` ## Commentary The `slugify` filter can be used to coerce an integer in to a string in a template. Consider the following use case: ```django ``` Because `order` is passed on the querystring, it will be a string, but `forloop.counter0` will be an integer, so the two will never be equal. Coercing `forloop.counter0` to a string using `slugify` solves the problem. An alternative would be to coerce `request.GET.order` in to an integer using the [`add` filter as shown here](/filters/add/). --- title: '|stringformat' description: formats a string. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/stringformat/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#stringformat --- # |stringformat formats a string. ## Documentation Formats the value using the [old printf-style string formatting.](https://docs.python.org/3/library/stdtypes.html#old-string-formatting) #### Variable ```django pi = math.pi ``` #### Template ```django {{ pi|stringformat:'E' }} ``` #### Result ```django 3.141593E+00 ``` ## Commentary For some types of websites, this might be super useful, but we find our strings are usually stored in the format in which we want to output them. And for numbers [`floatformat`](/filters/floatformat/) is generally more useful. One case where `stringformat` can be useful: comparing a value on the querystring, which is always a string, with an integer property of an object (e.g., an id). For example: ```django ``` Thanks to Simeon Visser for [this Stack Overflow answer](https://stackoverflow.com/a/27771117/5128561). --- title: '|striptags' description: strips HTML tags. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/striptags/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#striptags --- # |striptags strips HTML tags. ## Documentation Strips HTML tags. #### Variable ```django poem_html = '''
Much to his Mum and Dad’s dismay,
Horace ate himself one day.

He didn’t stop to say his grace,
He just sat down and ate his face.
“We can’t have this!” His Dad declared,
“If that lad’s ate, he should be shared.
''' ``` #### Template ```django {{ poem_html|striptags }} ``` #### Result ```django Much to his Mum and Dad’s dismay, Horace ate himself one day. He didn’t stop to say his grace, He just sat down and ate his face. “We can’t have this!” His Dad declared, “If that lad’s ate, he should be shared.” ``` ## Commentary This can be useful for converting a template HTML email to text when you want to send both HTML and text version of an email. --- title: '|time' description: for formatting times. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/time/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#time --- # |time for formatting times. ## Documentation Used to format the time of a `datetime`, `date` or `time` object. #### Variable ```django moon_landing = datetime.datetime(year=1969, month=7, day=21, hour=2, minute=56, second=15, tzinfo=datetime.timezone.utc) ``` #### Sample Formats - `{{ moon_landing }}` – July 21, 1969, 2:56 a.m. - `{{ moon_landing|time }}` – 2:56 a.m. - `{{ moon_landing|time:'G:i:s'}}` – 02:56:15 a.m. ## Commentary If you want output both the date and time, use the [`date`](/filters/date/) filter instead. --- title: '|timesince' description: outputs the amount of time between the value and `to_date`. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/timesince/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#timesince --- # |timesince outputs the amount of time between the value and `to_date`. ## Documentation Outputs the amount of time between the value and the `to_date` argument, which defaults to the current time. #### Variables ```django launch_date = datetime.datetime(year=1969, month=7, day=16, hour=13, minute=32, second=0, tzinfo=datetime.timezone.utc) moon_landing = datetime.datetime(year=1969, month=7, day=21, hour=2, minute=56, second=15, tzinfo=datetime.timezone.utc) ``` #### Template ```django {{ moon_landing|timesince }}
{{ launch_date|timesince:moon_landing }} ``` #### Result ```django 50 years, 8 months
4 days, 13 hours ``` The output in the browser will look like this: 50 years, 8 months 4 days, 13 hours - The first time period is the amount of time that has passed since the moon landing (based on the time this documentation is being written). - The second time period is the time between the rocket launch and the moment Neil Armstrong stepped on the moon. ## Commentary This is commonly used to output how much time has passed since an article was written (e.g., Posted 1 year, 2 months ago). --- title: '|timeuntil' description: outputs the amount of time between `from_date` and the value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/timeuntil/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#timeuntil --- # |timeuntil outputs the amount of time between `from_date` and the value. ## Documentation Outputs the amount of time between the `from_date` argument, which defaults to the current time and the value. #### Variables ```django century22 = datetime.datetime(year=2100, month=1, day=1, tzinfo=datetime.timezone.utc) moon_landing = datetime.datetime(year=1969, month=7, day=21, hour=2, minute=56, second=15, tzinfo=datetime.timezone.utc) ``` #### Template ```django {{ century22|timeuntil }}
{{ century22|timeuntil:moon_landing }} ``` #### Result ```django 79 years, 8 months
130 years, 5 months ``` The output in the browser will look like this: 79 years, 8 months 130 years, 5 months - The first time period is the amount of time left until the start of the 22nd century (based on the time this documentation is being written). - The second time period is the time between the moon landing and the start of the 22nd century. ## Commentary This is commonly used to output how much time is remaining before some event takes place (e.g., Sale ends in 9 hours, 50 minutes). --- title: '|title' description: capitalizes the first letter of each word in a value. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/title/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#title --- # |title capitalizes the first letter of each word in a value. ## Documentation Capitalizes the first letter of a value. #### Variable ```django greeting = 'hello, world!' ``` #### Template ```django {{ greeting|title }} ``` #### Result ```django Hello, World! ``` ## Commentary For web pages, formatting tags like this are not too useful. We prefer using CSS's `text-transform: capitalize` property. However, there is an advantage to using Django: because the formatting is applied server-side, the value returned to the client will already be formatted appropriately. If the client does not support CSS or has CSS turned off, that will not affect the formatting. And, of course, if you are using Django to output plain text or some other non-HTML format, formatting filters could come in handy. --- title: '|truncatechars' description: truncates a value to `n` characters and appends an ellipsis (…). date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/truncatechars/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#truncatechars --- # |truncatechars truncates a value to `n` characters and appends an ellipsis (…). ## Documentation Truncates a value to `n` characters and appends an ellipsis (…). #### Variable ```django blurb_text = 'You are pretty smart!' ``` #### Template ```django {{ blurb_text|truncatechars:15 }} ``` #### Result ```django You are pretty… ``` ## Commentary You should not use the `truncatechars` filter on HTML pages. Use [`truncatechars_html`](/filters/truncatechars_html/) instead. --- title: '|truncatechars_html' description: >- truncates a value to `n` characters and appends an ellipsis (…). Smart about HTML tags. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/truncatechars_html/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#truncatechars-html --- # |truncatechars_html truncates a value to `n` characters and appends an ellipsis (…). Smart about HTML tags. ## Documentation Truncates a value to `n` characters and appends an ellipsis (…). It does not count HTML tags as characters and closes any tags that were left open as a result of the truncation. #### Variable ```django blurb = '

You are pretty smart!

' ``` #### Template ```django {{ blurb|truncatechars_html:15 }} ``` #### Result ```django

You are pretty…

``` #### Autoescaping Be aware that autoescaping is on by default in Django. If you do not turn it off, either with the [`{% autoescape off %}`](/tags/autoescape) tag or the [`safe`](/filters/safe) filter, the HTML will be escaped. The easiest way to avoid this is to chain on the `safe` filter: ```django {{ blurb|truncatechars_html:15|safe }} ``` ## Commentary If you do not want to break off in the middle of a word, use [`truncatewords_html`](/filters/truncatewords_html/) instead. --- title: '|truncatewords' description: truncates a value to `n` words and appends an ellipsis (…). date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/truncatewords/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#truncatewords --- # |truncatewords truncates a value to `n` words and appends an ellipsis (…). ## Documentation Truncates a value to `n` words and appends an ellipsis (…). #### Variable ```django blurb_text = 'You are pretty smart!' ``` #### Template ```django {{ blurb_text|truncatewords:3 }} ``` #### Result ```django You are pretty… ``` ## Commentary You should not use the `truncatewords` filter on HTML pages. Use [`truncatewords_html`](/filters/truncatewords_html/) instead. See also: - [`truncatechars`](/filters/truncatechars/) - [`truncatechars_html`](/filters/truncatechars_html/) - [`truncatewords`](/filters/truncatewords/) - [`truncatewords_html`](/filters/truncatewords_html/) --- title: '|truncatewords_html' description: >- truncates a value to `n` words and appends an ellipsis (…). Smart about HTML tags. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/truncatewords_html/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#truncatewords-html --- # |truncatewords_html truncates a value to `n` words and appends an ellipsis (…). Smart about HTML tags. ## Documentation Truncates a value to `n` words and appends an ellipsis (…). It does not count HTML tags as words and closes any tags that were left open as a result of the truncation. #### Variable ```django blurb = '

You are pretty smart!

' ``` #### Template ```django {{ blurb|truncatewords_html:3 }} ``` #### Result ```django

You are pretty…

``` #### Autoescaping Be aware that autoescaping is on by default in Django. If you do not turn it off, either with the [`{% autoescape off %}`](/tags/autoescape) tag or the [`safe`](/filters/safe) filter, the HTML will be escaped. The easiest way to avoid this is to chain on the `safe` filter: ```django {{ blurb|truncatewords_html:3|safe }} ``` ## Commentary This is our favorite of the [truncating filters](/search/?q=truncat). --- title: '|unordered_list' description: creates an unordered HTML list from a Python list of lists. date: '2025-12-04' categories: - Filter canonical: https://www.djangotemplatetagsandfilters.com/filters/unordered_list/ doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#unordered-list --- # |unordered_list creates an unordered HTML list from a Python list of lists. ## Documentation Creates an unordered HTML list from a Python list that contains other lists, which also may contains lists, etc. You must add the outermost `