如何在Django模板中检查变量是否为“False”?

85 投票
13 回答
161305 浏览
提问于 2025-04-16 07:21

我怎么用Django模板语法来检查一个变量是否是False呢?

{% if myvar == False %}

这个方法好像不行。

需要注意的是,我特别想检查这个变量是否是Python中的False值。这个变量也可能是一个空数组,但我并不想检查这个。

13 个回答

44

我觉得这个对你有帮助:

{% if not myvar %}
51

为了后人留个记录,我有几个 NullBooleanField,这是我处理它们的方法:

要检查它是否是 True

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

要检查它是否是 False(注意,因为只有三种值——True/False/None,所以这样做是有效的):

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

要检查它是否是 None

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

我不太明白为什么,我不能用 variable == False 来检查,但我可以用 variable == None

45

Django 1.10的更新说明中新增了isis not这两个比较运算符,可以在if标签中使用。这一变化让在模板中进行身份测试变得非常简单。

In[2]: from django.template import Context, Template

In[3]: context = Context({"somevar": False, "zero": 0})

In[4]: compare_false = Template("{% if somevar is False %}is false{% endif %}")
In[5]: compare_false.render(context)
Out[5]: u'is false'

In[6]: compare_zero = Template("{% if zero is not False %}not false{% endif %}")
In[7]: compare_zero.render(context)
Out[7]: u'not false'

如果你使用的是较旧版本的Django,从1.5版本开始,更新说明中提到,模板引擎会把TrueFalseNone解释为对应的Python对象。

In[2]: from django.template import Context, Template

In[3]: context = Context({"is_true": True, "is_false": False, 
                          "is_none": None, "zero": 0})

In[4]: compare_true = Template("{% if is_true == True %}true{% endif %}")
In[5]: compare_true.render(context)
Out[5]: u'true'

In[6]: compare_false = Template("{% if is_false == False %}false{% endif %}")
In[7]: compare_false.render(context)
Out[7]: u'false'

In[8]: compare_none = Template("{% if is_none == None %}none{% endif %}")
In[9]: compare_none.render(context)
Out[9]: u'none'

不过,这个功能的表现可能和你预期的有所不同。

In[10]: compare_zero = Template("{% if zero == False %}0 == False{% endif %}")
In[11]: compare_zero.render(context)
Out[11]: u'0 == False'

撰写回答