简体   繁体   中英

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:

{% 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. I tried no quotes {% if content.show_in_news == True %} Also tried all lowercase true, or just {% if content.show_in_news %} No luck.

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:

{% 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. Since the form field itself exists, the conditional always evaluates as true. Annoying.

You can make it work like you expect by using the value explicitly, like so:

{% if content.show_in_news.value %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM