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?
Example:
{% if some_var == 3 %}
working
{% 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 %}
working
{% endif %}

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

Comments

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

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

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

    ReplyDelete
  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.

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

    ReplyDelete
  6. Thanks for sharing. Django is the powerful framework of Python. Kanhasoft is the leading Django web development company in India and USA. With the team of 45 experienced Web developers, we are outsourcing mobile and web application services to Canada, USA, Denmark, Australia, South Africa and more.

    ReplyDelete

Post a Comment

Popular posts from this blog

Top things to do after installing Manjaro KDE

PIP - upgrade all packages from requirements.txt (interactively)