'collapsing accordion content in django for loop

I am trying to implement for loop in my accordion. Everything seems to be fine except the fact that when I click on 3rd or 4th button then other bodies stay expanded. It should work exactly the same as in the first example in Bootstrap documentation so if you click on Accordion Item #2 then Accordion Item #1 and Accordion Item #3 collapse.

I am sure that the issue is with my {% if forloop.first %} but I am not sure how can I dynamically change that so it will collapse all accordion contents except active one.

My code:

  {% for category in top_categories %}
  <div class="accordion" id="accordionExample">
    <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="false" aria-controls="collapse{{category.id}}">
          {{category.title}}
        </button>
      </h2>
      <div id="collapse{{category.id}}" class="accordion-collapse {% if forloop.first %} show {% else %} collapse {% 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>
  </div>
  {% endfor %}


Solution 1:[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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1