Django templates: If false?

2020-02-16 23:17发布

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.

10条回答
Luminary・发光体
2楼-- · 2020-02-16 23:31

I think this will work for you:

{% if not myvar %}
查看更多
相关推荐>>
3楼-- · 2020-02-16 23:35

I have had this issue before, which I solved by nested if statements first checking for none type separately.

{% if object.some_bool == None %}Empty
{% else %}{% if not object.some_bool %}False{% else %}True{% endif %}{% endif %}

If you only want to test if its false, then just

{% if some_bool == None %}{% else %}{% if not some_bool %}False{% endif %}{% endif %}

EDIT: This seems to work.

{% if 0 == a|length %}Zero-length array{% else %}{% if a == None %}None type{% else %}{% if not a %}False type{% else %}True-type {% endif %}{% endif %}{% endif %}

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

{% if some_bool in false_list %}False {% endif %}
查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-16 23:35

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-16 23:41

I've just come up with the following which is looking good in Django 1.8

Try this instead of value is not False:

if value|stringformat:'r' != 'False'

Try this instead of value is True:

if value|stringformat:'r' == '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.

查看更多
兄弟一词,经得起流年.
6楼-- · 2020-02-16 23:42

For posterity, I have a few NullBooleanFields and here's what I do:

To check if it's True:

{% if variable %}True{% endif %}

To check if it's False (note this works because there's only 3 values -- True/False/None):

{% if variable != None %}False{% endif %}

To check if it's None:

{% if variable == None %}None{% endif %}

I'm not sure why, but I can't do variable == False, but I can do variable == None.

查看更多
可以哭但决不认输i
7楼-- · 2020-02-16 23:43

This is far easier to check in Python (i.e. your view code) than in the template, because the Python code is simply:

myvar is False

Illustrating:

>>> False is False
True
>>> None is False
False
>>> [] is False
False

The problem at the template level is that the template if doesn't parse is (though it does parse in). Also, if you don't mind it, you could try to patch support for is into the template engine; base it on the code for ==.

查看更多
登录 后发表回答