简体   繁体   English

Django模板:如何根据模型中的布尔字段显示HTML块

[英]Django Templates: How to display block of HTML based on a boolean field in model

Having a strange problem. 有一个奇怪的问题。 Let's say, in my Content model: 比方说,在我的内容模型中:

show_in_posts = models.BooleanField()
show_in_news = models.BooleanField()
show_in_updates = models.BooleanField()

Then in my {% for content in contents %} template: 然后在我的{% for content in contents %}模板中:

{% if content.show_in_news == 'True' %}
   ....
{% endif %}

Can't seem to get the condition to work. 似乎无法让条件起作用。 It seems {{ content.show_in_news }} always evaluates as True, even if the it's set in the Admin panel as unchecked. 似乎{{ content.show_in_news }}总是评估为True,即使它在管理面板中设置为未选中。 I tried no quotes {% if content.show_in_news == True %} Also tried all lowercase true, or just {% if content.show_in_news %} No luck. 我试过没有引号{% if content.show_in_news == True %}同时尝试全部小写为true,或者只是{% if content.show_in_news %}没有运气。

Some other post suggested registering a custom 'filter' but this seems so trivial, should work out of the box? 其他一些帖子建议注册一个自定义的“过滤器”,但这似乎是微不足道的,应该开箱即用吗?

Assistance much appreciated! 非常感谢!

You can use for match BooleanField condition: 您可以使用匹配BooleanField条件:

{% ifequal content.show_in_news True %}
    Your code here
{% endifequal %}

Or like this 或者像这样

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

I just ran into this too. 我也碰到了这个。 What was happening was Django's {% if expr %} evaluates true if the expr exists and is not None. 发生的事情是Django的{%if expr%}如果expr存在并且不是None,则求值为true。 Since the form field itself exists, the conditional always evaluates as true. 由于表单字段本身存在,因此条件总是计算为true。 Annoying. 烦人。

You can make it work like you expect by using the value explicitly, like so: 您可以通过显式使用值使其按预期工作,如下所示:

{% if content.show_in_news.value %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在HTML页面上显示模型字段-Django - How to display model field on html page - Django 如何将 boolean 字段输入从 HTML 带入我的 Django Z20F35E630DAF44DBFA4C3F68F53998D? - How to take boolean field input from HTML into my Django model? Django model 基于boolean字段过滤 - Django model filter based on boolean field 如何将Django模型布尔值字段更新为true? - How to update Django model Boolean field as true? 如何在 Django 中修改布尔字段模型? - How to modify a boolean field model in Django? 如何在 Django 模板中只显示具有相同数据的模型字段值一次? - How to only display model field value with same data only once in Django templates? django - 如何在“base.html”中显示来自模型的列表对象并将其扩展到所有其他模板 - django - how to display list objects from model in 'base.html' and extends it to all other templates Django:如何在 Django 模板(html 文件)中减去两个 model 字段? - Django: How to subtract two model fields in Django templates(html file)? 如何在Django模板中显示下拉字段__str__? - How to display a dropdown field __str__ in Django templates? 如何在基于 class 的视图的 django 模板中使用 model 方法 - How to use model methods in django templates with class based view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM