Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django模板:如何基于模型中的布尔字段显示HTML块_Python_Django_Templates_Boolean_Conditional Statements - Fatal编程技术网

Python Django模板:如何基于模型中的布尔字段显示HTML块

Python Django模板:如何基于模型中的布尔字段显示HTML块,python,django,templates,boolean,conditional-statements,Python,Django,Templates,Boolean,Conditional Statements,有一个奇怪的问题。比如说,在我的内容模型中: show_in_posts = models.BooleanField() show_in_news = models.BooleanField() show_in_updates = models.BooleanField() 然后在我的{%中,对于contents%}模板中的内容: {% if content.show_in_news == 'True' %} .... {% endif %} 似乎无法使条件发挥作用。似乎{{conte

有一个奇怪的问题。比如说,在我的内容模型中:

show_in_posts = models.BooleanField()
show_in_news = models.BooleanField()
show_in_updates = models.BooleanField()
然后在我的
{%中,对于contents%}
模板中的内容:

{% if content.show_in_news == 'True' %}
   ....
{% endif %}
似乎无法使条件发挥作用。似乎
{{content.show_in_news}}
总是计算为True,即使它在管理面板中设置为未选中。我尝试了不使用引号
{%if content.show_in_news==True%}
也尝试了所有小写的True,或者只是
{%if content.show_in_news%}
没有运气

其他一些帖子建议注册一个自定义的“过滤器”,但这看起来很简单,应该开箱即用吗


非常感谢您的帮助

可用于匹配布尔场条件:

{% ifequal content.show_in_news True %}
    Your code here
{% endifequal %}
或者像这样

{% if content.show_in_news %}
   your code here
{% endif %}

我也遇到了这个。发生的是Django的{%if expr%}在expr存在而不是无的情况下计算为true。由于表单字段本身存在,因此条件字段的计算结果始终为true。讨厌

通过显式使用该值,可以使其按预期工作,如下所示:

{% if content.show_in_news.value %}

{{content.show_in_news}}
为您提供了什么?根据上面的说明,似乎总是
True
,即使在管理员界面中没有选中复选框,但肯定有问题。即使是我的其他布尔值,当它们在DB中被明确设置为Off时,也会在模板中打印为“True”。我可以在“管理”和“保存”中切换它们——它们变为红色的“停止标志”图标,切换回“保存”和“绿色复选标记”——所有这些都可以正常工作。我只是不能让他们通过模板通过,因为除了真的。其他类型,如CharField、TextArea显示良好。。呃,给出了什么:(你能告诉我们你的观点吗?你能告诉我们你在做什么查询来获取
内容吗?