Reputation: 3080
How can I distinguish between None
and False
in django templates?
{% if x %}
True
{% else %}
None and False - how can I split this case?
{% endif %}
Upvotes: 15
Views: 5702
Reputation: 308959
Every Django template context contains True
, False
and None
. For Django 1.10 and later, you can do the following:
{% if x %}
True
{% elif x is None %}
None
{% else %}
False (or empty string, empty list etc)
{% endif %}
Django 1.9 and earlier do not support the is
operator in the if
tag. Most of the time, it is ok to use {% if x == None %}
instead.
{% if x %}
True
{% elif x == None %}
None
{% else %}
False (or empty string, empty list etc)
{% endif %}
With Django 1.4 and earlier, you do not have access to True
, False
and None
in the template context, You can use the yesno
filter instead.
In the view:
x = True
y = False
z = None
In the template:
{{ x|yesno:"true,false,none" }}
{{ y|yesno:"true,false,none" }}
{{ z|yesno:"true,false,none" }}
Result:
true
false
none
Upvotes: 16
Reputation: 17616
Here is another tricky way:
{% if not x.denominator %}
None
{% else %}
{% if x %}
True
{% else %}
False
{% endif %}
{% endif %}
That's because "None" doesn't have the attribute "denominator", while it is 1 for both "True" and "False".
Upvotes: 0
Reputation: 7746
Create context_processor (or use from the django-misc module misc.context_processors.useful_constants
) with True
, False
, None
constants and use {% if x == None %}
or {% if x == False %}
context_processor.py
:
def useful_constants(request):
return {'True': True, 'False': False, 'None': None}
Upvotes: 0
Reputation: 9749
An enhancement of the previous answers could be:
{% if x|yesno:"2,1," %}
# will enter here if x is True or False, but not None
{% else %}
# will enter only if x is None
{% endif %}
Upvotes: 3
Reputation: 375674
You can create a custom filter:
@register.filter
def is_not_None(val):
return val is not None
then use it:
{% if x|is_not_None %}
{% if x %}
True
{% else %}
False
{% endif %}
{% else %}
None
{% endif %}
Of course, you could tweak the filter to test whatever condition you like also...
Upvotes: 5