Distinguishing between False and 0 (zero) in a Django template

June 27

You may occasionally find yourself in a Django template attempting to distinguish if False is not equal to 0 (bool vs. int).

There are multiple ways to accomplish this, but if you don’t want to create a new template tag, and you don’t want to add logic to the view (because you’re a rebel), you can accomplish it using the “add” filter.

Take the variable “my_var”

If my_var is a ‘bool’ False:

my_var|add:"f" == "f"


If my_var is an ‘int’ 0:

my_var|add:"f" == ""


And all together now:

{% if my_var|add:"f" == "f" %}
    I have a boolean False
{% else %}
    I have a 0
{% endif %}


Keep in mind that this logic may vary depending what you’re comparing.  It’s useful as is ONLY if you know you’re trying to distinguish between False and zero (0).  If you can have values for my_var like “” or [] or other data types that have certain scenarios for equating with False, you’ll have to play around, but I personally had difficulty finding answers that address this that didn’t involve building logic outside of the template file itself.


Posted by on June 27, 2014 in Computers, Programming, Uncategorized

Leave a comment

Tags: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *