1

Context

I'm trying to fill a bootstrap 4 accordion with dynamically created django forms.

Description

Starting from the example given here, I'm trying to build an accordion component a from a formset composed of an undefined amount of forms (they are dynamically created).

I want all the the accordion cards to be collapsed, except for the first one at the initial step.

I would like one card per form.

What I currently have

I currently have something like this:

<div id="accordion">
  {% for form in formset %}

      <div class="card">

        <div id="heading_{{ forloop.counter }}" class="card-header">
          <h5 class="mb-0">
            <button class="btn btn-link" data-toggle="collapse" 
             data-target="#collapse_{{ forloop.counter }}" 
             aria-expanded="{% if forloop.counter == 1 %}
                             {{ true }}
                           {% else %}
                             {{ false }}
                           {% endif %}" 
             aria-controls="collapse_{{ forloop.counter }}">
              Form id is: {{ forloop.counter }} 
            </button>
          </h5>
        </div>

        <div id="collapse_{{ forloop.counter }}" class="collapse" 
         aria-labelledby="heading_{{ forloop.counter }}"
         data-parent="#accordion">
          <div class="card-body">
            {{ form.media }} # the actual content of the form
            {% bootstrap_form form layout='horizontal' %}
          </div>
        </div>

      </div>
  <hr>
  {% endfor %}
</div>

But this is buggy, my forms are displayed as collapsed cards and when I open one by clicking on it, it immediately closes.

I also tested with a card <div id="collapse_{{ forloop.counter }}" class="collapse show" after reading this but it makes all cards open at once, and here it's the opposite; when I close one, it immediately opens again.

I also tried to change for both the previous cases, aria-expanded="false" to aria-expanded="true" in the header but this doesn't change the behavior in any of the two cases.

I also tried to remove data-parent=#accordion from the card div as explained here but with no success.

Edit 2020-04-07:

Instead of setting the attribute:

aria-expanded="true"

I set it like that:

aria-expanded="{% if forloop.counter == 1 %}
                 {{ true }}
               {% else %}
                 {{ false }}
               {% endif %}" 

But it doesn't change the general behavior.



Info

Boostrap version is: 4.1.1/css/bootstrap.min.css
And Django version: 2.2.6.

swiss_knight
  • 5,787
  • 8
  • 50
  • 92

0 Answers0