How do I check if a variable is False using Django template syntax?
{% if myvar == False %}
Doesn't seem to work.
Note that I very specifically want to check if it has the Python value False
. This variable could be an empty array too, which is not what I want to check for.
I think this will work for you:
I have had this issue before, which I solved by nested if statements first checking for none type separately.
If you only want to test if its false, then just
EDIT: This seems to work.
Now zero-length arrays are recognized as such; None types as None types; falses as False; Trues as trues; strings/arrays above length 0 as true.
You could also include in the Context a variable false_list = [False,] and then do
Look at the yesno helper
Eg:
I've just come up with the following which is looking good in Django 1.8
Try this instead of value is not False:
Try this instead of value is True:
unless you've been really messing with repr methods to make value look like a boolean I reckon this should give you a firm enough assurance that value is True or False.
For posterity, I have a few
NullBooleanField
s and here's what I do:To check if it's
True
:To check if it's
False
(note this works because there's only 3 values -- True/False/None):To check if it's
None
:I'm not sure why, but I can't do
variable == False
, but I can dovariable == None
.This is far easier to check in Python (i.e. your view code) than in the template, because the Python code is simply:
Illustrating:
The problem at the template level is that the template
if
doesn't parseis
(though it does parsein
). Also, if you don't mind it, you could try to patch support foris
into the template engine; base it on the code for==
.