[Answered ]-Collapsing accordion content in django for loop

1๐Ÿ‘

I think that the main problem is that you are including <div class"accordion" id="accordionExample"> inside the loop. A secondary one is that the "collapse" class is also necessary for the first iteration. Try this:

<div class="accordion" id="accordionExample">
  {% for category in top_categories %}
    <div class="accordion-item">
      <h2 class="accordion-header" id="heading{{category.id}}">
        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{category.id}}" aria-expanded="true" aria-controls="collapse{{category.id}}">
          {{category.title}}
        </button>
      </h2>
      <div id="collapse{{category.id}}" class="accordion-collapse collapse {% if forloop.first %}show{% endif %}" aria-labelledby="heading{{category.id}}" data-bs-parent="#accordionExample">
        <div class="accordion-body">
          {% for qa in category.qa.all|slice:"0:3" %}
            <a href="{{ qa.get_absolute_url }}">Q: {{qa}}</a><hr>
          {% endfor %}
        </div>
      </div>
    </div>
  {% endfor %}
</div>

Leave a comment