[英]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.