Zack Plauché
Zack Plauché

Reputation: 4240

Django Jinja - If an object in all objects has attribute run html

I'm needing help figuring out how to write code for this problem (in title).

Let's say I have this model:

from django.db import models

class Section(models.Model):
    name = models.CharField(max_length=20)
    display = models.BooleanField(default=True)

and I create 2 objects with different names and 2 different display variables:

>>> s1.display
True
>>> s2.display
False

Here I have some HTML code with Jinja templating for this code to display, if these objects even exist:

<!-- In Views, Section.objects.all() is 'sections' -->

{% if sections %}
<div class="all-sections">
  <h2 class="title">Explore</h2>
  {% for section in sections %}
  <div class="section">
    <p class="section-title">{{ section.name }}</p>
  </div>
  {% endfor %}
</div>
{% endif %}

Now I make both of them false:

>>> s1.display = False
>>> s1.save()

Now, if ALL OF THEM HAVE DISPLAY FALSE I don't want the entire section to be there, the same as if there weren't any in that list at all.

I've thought about doing a for loop and iterating through each one, but then that would just repeat the all of the HTML code for each one that did have display on.

<!-- Wouldn't Work Example -->
{% if sections %}
  {% for section in sections %}
    {% if section.display %}
      <div class="all-sections">
        <h2 class="title">Explore</h2>
        {% for section in sections %}
          <div class="section">
            <p class="section-title">{{ section.name }}</p>
          </div>
        {% endfor %}
      </div>
    {% endif %}
  {% endfor %}
{% endif %}

How would you do it to where the whole section doesn't show if there are objects but none of them have "display = True"?

Upvotes: 0

Views: 578

Answers (1)

Maharshi
Maharshi

Reputation: 232

It is best to filter the queryset in view not in template.

qs = Section.objects.filter(display=True)

Pass this queryset as context.

Upvotes: 1

Related Questions