Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

Django BooleanField if statement doesnt return content

For some reason when checking to see if BooleanField post.featured is true I get no output. If I remove that it works fine but not as I intend.

<div class="carousel-inner">
    {% for post in object_list%}
        {% if post.featured is True %}<!-- This post.featured is BooleanField -->
            {% if forloop.first %}
                <div class="carousel-item active">
            {% else %}
                <div class="carousel-item">
            {% endif %}
                    <div class="col-md-6 px-0">
                        <h1 class="display-4 font-italic">{{ post.title }}</h1>
                        <p class="lead my-3">{{ post.hook }}</p>
                        <p class="lead mb-0">
                           <a href="{% url 'article-details' post.pk %}" class="text-white fw-bold">
                               Continue reading...
                           </a>
                        </p>           
                    </div>
                </div>
        {% endif %}<!-- and this -->
    {% endfor %}
</div>

Heres how it looks like when not checking if post.featured == true:

Working

However, content doesnt render with {% if post.featured is True %} or {% if post.featured %}

Can someone please explain what im doing wrong

EDIT: Submiting my view:

class Home(ListView):
    model = Post
    template_name = 'home.html'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should not filter in the template. This is not only inefficient, but a template is not meant to implement business logic, only rendering logic: a template should not be concerned with what it renders, it should only be concerned with rendering the data in a pleasant way.

You should filter in the ListView:

class Home(ListView):
    model = Post
    template_name = 'home.html'
    queryset = Post.objects.filter(featured=True)

This will filter at the database side.

If you need both the featured items, and the ones that are not featured, you can make two queries:

class Home(ListView):
    model = Post
    template_name = 'home.html'
    queryset = Post.objects.filter(featured=True)

    def non_featured(self):
        return Post.objects.filter(featured=False)

then you can render the non-featured items with:

{% for post in view.non_featured %}
    …
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...