Compare integer variable in django templates

Ever needed to compare some variable (that may come from db, forms, etc) in django templates with an integer?
{% if some_var == 3 %}
{% endif %}

The above example will not work. Django's template engine interprets the variable as a string.

Workaround for integer comparison:
{% if some_var|add:0 == 3 %}
{% endif %}

By using the "add" filter, the variable is transformed into an integer.


  1. you can use {% if some_var == '3' %}

  2. It works, but only for equal comparison :)

  3. Yes, but if I want to compare between numbers such as 'a > b', any way to do this?

  4. {% if a|add:0 > b|add:0 %}

    But don't write too much logic in templates.
    Data should already come prepared for the template.
    That's why django does not allow complex comparisons, with "and" and "or" combined.

  5. Oh, yes, it's so kind of you, thank you for your help~


Post a Comment

Popular posts from this blog

Improve font rendering for IntelliJ IDEA / Pycharm in Ubuntu

Fix - Updated from OSX El Capitan Gold Master to Final Release, andbeta update keeps showing in AppStore