add Filter

Number

Argument: arg (required) – an integer or string to add to the value.

Documentation

Adds arg to the value. This can be used for adding numbers or concatenating strings.

Variables

age = 30
name = 'Nat'

Template

{{ name|'haniel' }} is {{ age|add:20 }}.

Result

Nathaniel is 50.

Commentary

The add filter can be used to coerce a string in to an integer in a template. Consider the following:

<select name="order">
  {% for field in order_fields %}
    <option value="{{ forloop.counter0 }}"
      {% if request.GET.order|add:"0" == forloop.counter0 %}selected{% endif %}
    >{{ field }}</option>
  {% endfor %}
</select>

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.


Did we get something wrong? Is there a use case for the add filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on May 12, 2020, 8:45 a.m. EST