user11846186
user11846186

Reputation:

How to do an if statement in a Django template to find if a decimal value is 0

Basically, I want to find out if a decimal field value is 0.00. Then, I want to output a different value in the template. See code below. The code does not work.

variable = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) 

#template

{% for item in table %}
{% if item.variable is 0.00 %}
      <li><strong>Total: </strong> Unknown </li>
{% else %}
      <li><strong>Total:</strong> ${{ item.variable }}</li>
{% endif %}
{% endfor %}

This does not work. It outputs: Total: $0.00.

Upvotes: 2

Views: 1177

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can check this with if not item.variable for example, since 0.00 has truthiness False. This condition will also check if the value is None (so NULL in the database), which is probably something you should consider as well:

{% for item in table %}
    {% if not item.variable %}
        <li><strong>Total: </strong> Unknown </li>
    {% else %}
        <li><strong>Total:</strong> ${{ item.variable }}</li>
    {% endif %}
{% endfor %}

If you only want to check for zero, you can check it with == 0:

{% for item in table %}
    {% if item.variable == 0 %}
        <li><strong>Total: </strong> Unknown </li>
    {% else %}
        <li><strong>Total:</strong> ${{ item.variable }}</li>
    {% endif %}
{% endfor %}

Upvotes: 2

Related Questions