Formset и django-autocomplete-light создают дополнительное значение

Formset создает дополнительное значение, когда я нажимаю кнопку "добавить еще одно".enter image description here Не знаю, как это исправить. Я буду рад, если вы сможете дать мне совет. Более того, вторая строка не работает, то есть я не могу выбрать никакое значение. Она не показывает никаких вариантов.

forms.py

class BirdForm(forms.ModelForm):
    name = forms.ModelChoiceField(
        queryset=Bird.objects.all(),
        widget=autocomplete.ModelSelect2(
            url='birdautocomplete'),
    )

    class Meta:
        model = Bird
        fields = ('name', 'description')

BirdFormSet = modelformset_factory(
    Bird, form=BirdForm, extra=1,
)

template.html

         <div class="check_bird form-row">
            <label class="form-label" for="myCheck">If you want to add new bird</label>
            <input type="checkbox" id="myCheck" onclick="FunctionBird()">
         </div>

         <div class="check_bird_form" id="bird" style="display:none">
            {{formset.management_form}}
            {% for form in formset %}
            <div class="bird-form form-row">
               {{form}}
            </div>
            {% endfor %}
            <button style="margin-top:25px;" id="add-form" type="button">Add Another</button>
         </div>
         {{formset.media}}

<script>
   function BirdCoauthor() {
      var checkBox = document.getElementById("myCheck");
      var text = document.getElementById("bird");
      if (checkBox.checked == true) {
         text.style.display = "block";
      } else {
         text.style.display = "none";
      }
   }

   let birdForm = document.querySelectorAll(".bird-form")
   let container = document.querySelector("#coauthor")
   let addButton = document.querySelector("#add-form")
   let totalForms = document.querySelector("#id_form-TOTAL_FORMS")

   let formNum = birdForm.length - 1
   addButton.addEventListener('click', addForm)

   function addForm(e) {
      e.preventDefault()

      let newForm = birdForm[0].cloneNode(true)
      let formRegex = RegExp(`form-(\\d){1}-`, 'g')

      formNum++
      newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
      container.insertBefore(newForm, addButton)

      totalForms.setAttribute('value', `${formNum+1}`)
   }

   $("#1").val(null).trigger("change");
</script>
Вернуться на верх