16đź‘Ť
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
5đź‘Ť
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…
- Django: values_list() multiple fields concatenated
- Django Queryset to dict for use in json
- Ignoring case with __startswith
- How should multiple Django apps communicate with each other?
3đź‘Ť
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 %}
- How to compare version string ("x.y.z") in MySQL?
- Has_permission() missing 1 required positional argument: 'view'
- Django how to override clean() method in a subclass of custom form?
- Use a django built in filter in code (outside of a template)
0đź‘Ť
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}
- In Django, How do I get escaped html in HttpResponse?
- Next previous links from a query set / generic views
- Django – specify database for TestCase fixtures
- Why use South during initial development?
- How to override template in django-allauth?
0đź‘Ť
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”.
- Django REST Framework: Validate before a delete
- Django getting the absolute path of a FileField
- Libmysqlclient.18.dylib image not found when using MySQL from Django on OS X
- Django channels and socket.io-client