stringformat Filter

String

Argument: format (required) – the string format.

Documentation

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 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:

<select name="user" id="user" class="form-select">
  <option value="">User</option>
  {% for user in users %}
    <option value="{{ user.id }}"{% if request.GET.user == user.id|stringformat:"i" %} selected{% endif %}>{{ user.full_name }}</option>
  {% endfor %}
</select>

Thanks to Simeon Visser for this Stack Overflow answer.


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

Send Feedback

Official Documentation
This page last updated on Oct. 30, 2022, 1:21 p.m. EST