title: Dynamic New Forms in Django
body: <p>I have this code and I want to create Dynamic New FormSet . By adding and deleting buttons
  in Models I have Customer, Product and AddProduct classes</p>
  <pre><code>class Customer(models.Model):
      customer = models.CharField(max_length=200, null=True, blank=False)
  
  class Product(models.Model):
      customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, related_name='customer_product')
      product = models.CharField(max_length=200,choices=PRODUCT, blank=False)
  
  
  class AddProduct(models.Model):
     customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True,related_name='customer_add_product')
     products = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='product_add_product')
     add_product = models.CharField(max_length=200, choices=PRODUCT, blank=True,null=True)
  </code></pre>
  <p>in forms</p>
  <pre><code>    class PersonCreationForm(forms.ModelForm):
         class Meta:
           model = Product
           fields = ['product']
  
  class AddProductForm(forms.ModelForm):
     class Meta:
        model = AddProduct
        fields = ['add_product']
  </code></pre>
  <p>in views</p>
  <pre><code> def CreateView(request, pk):
       customer = get_object_or_404(Customer, pk=pk)
           formset_addedFormset = modelformset_factory(AddProduct, form=AddProductForm)
      form = PersonCreationForm(request.POST or None)
      formset = formset_addedFormset(request.POST or None, queryset=AddProduct.objects.none(), prefix=&quot;product_add_product&quot;)
  
  if request.method == 'POST':
      if form.is_valid() and formset.is_valid():
          new_form = form.save(commit=False)
          new_form.customer=customer
          new_form.save()
          product = Product.objects.all().last()
          print(product)
  
          for add_product in formset:
              new_formset = add_product.save(commit=False)
              new_formset.customer=customer
              new_formset.products = product
              new_formset.save()
      else:
         print('error')
  context = {'customer':customer,
              'formset':formset,
              'form':form,
              }
  return render(request, create.html',context)
  </code></pre>
  <p>in create.html</p>
  <pre><code>   {% load crispy_forms_tags %}
     {% block content %}
     &lt;form method=&quot;POST&quot;&gt;
       {% csrf_token %}
                              &lt;!-- here for create Product --&gt;
                              {% for form in form %}
                                &lt;table&gt;
                                    
                                  &lt;td&gt;{{form.product|as_crispy_field}}&lt;/td&gt;
                                        {% endfor %}
                                        &lt;!-- end for --&gt;
  
                                     {{ formset.management_form }}
  
                                      {% for formset in formset.forms %}
   
                                      {{ formset.field_errors }}
                                      {{ formset.errors }}
                                      {% endfor %}
                                               {% for hidden in formset.hidden_fields %}
                                               {{ hidden }}
                                           {% endfor %}
  
                          &lt;!-- HERE for create Add_Product as Dynamic New FormSet --&gt;
                                    
                                      {% for formset in formset %}
                                      &lt;tr class=&quot;item&quot;&gt;
  
                                &lt;td&gt;{{ formset.add_product|as_crispy_field  }}&lt;/td&gt;
  
    &lt;td&gt;&lt;button type=&quot;button&quot; class=&quot;btn btn-danger btn-sm remove-form-row&quot;
                                       id=&quot;{{ formset.prefix }}&quot;&gt;Delete&lt;/button&gt;&lt;td&gt;
                                        &lt;/tr&gt;
                                       {% endfor %}
  
                             &lt;td colspan=&quot;9&quot;
                                          style=&quot;border-left: none!important; border- 
              right: none !important; border-bottom: none!important;&quot;&gt;
                                          &lt;button type=&quot;button&quot; class=&quot;btn btn-sm btn- 
                        success add-form-row&quot;
                                                  id=&quot;{{ formset.prefix }}&quot;&gt;
                                             Add
                                          &lt;/button&gt;
                                      &lt;/table&gt;
        &lt;hr&gt;
             &lt;input class=&quot;btn btn-secondary btn-lg mt-2&quot; type=&quot;submit&quot; value=&quot;submit&quot;&gt;
             
  
  
       &lt;/form&gt;
       {% endblock %}
  
       {% block extra_script %}
       &lt;script type=&quot;text/javascript&quot; src=&quot;{% static 'js/formset.js' %}&quot;&gt;&lt;/script&gt;
       &lt;script src=&quot;https://code.jquery.com/jquery-3.3.1.min.js&quot;&gt;&lt;/script&gt;
       {% endblock%}
  </code></pre>
  <p>in formset.js</p>
  <pre><code> function updateElementIndex(el, prefix, ndx) {
   var id_regex = new RegExp('(' + prefix + '-\\d+-)');
   var replacement = prefix + '-' + ndx + '-';
   if ($(el).attr(&quot;for&quot;)) $(el).attr(&quot;for&quot;, 
   $(el).attr(&quot;for&quot;).replace(id_regex,replacement));
   if (el.id) el.id = el.id.replace(id_regex, replacement);
   if (el.name) el.name = el.name.replace(id_regex, replacement);}
  
   function addForm(btn, prefix) {
   var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
   if (formCount &lt; 1000) {
      // Clone a form (without event handlers) from the first form
      var row = $(&quot;.item:last&quot;).clone(false).get(0);
  
      // Insert it after the last form
      $(row).removeAttr('id').hide().insertAfter(&quot;.item:last&quot;).slideDown(300);
      
      // Remove the bits we don't want in the new row/form
      // e.g. error messages
      $(&quot;.errorlist&quot;, row).remove();
      $(row).children().removeClass(&quot;error&quot;);
      
      // Relabel or rename all the relevant bits
      $(row).find('.formset-field').each(function () {
          updateElementIndex(this, prefix, formCount);
          $(this).val('');
          $(this).removeAttr('value');
          $(this).prop('checked', false);
      });
  
      // Add an event handler for the delete item/form link
      $(row).find(&quot;.delete&quot;).click(function () {
          return deleteForm(this, prefix);
      });
      // Update the total form count
      $(&quot;#id_&quot; + prefix + &quot;-TOTAL_FORMS&quot;).val(formCount + 1);
      
  
      } // End if
  
      return false;
      }
  
  
     function deleteForm(btn, prefix) {
     var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
     if (formCount &gt; 1) {
        // Delete the item/form
        var goto_id = $(btn).find('select','input','lable').val();
        if( goto_id ){
          $.ajax({
              url: &quot;/&quot; + window.location.pathname.split(&quot;/&quot;)[1] + &quot;/formset-data- 
           delete/&quot;+ goto_id +&quot;/?next=&quot;+ window.location.pathname,
              error: function () {
                console.log(&quot;error&quot;);
              },
              success: function (data) {
                $(btn).parents('.item').remove();                 
              },
              type: 'GET'
          });
        }else{
          $(btn).parents('.item').remove();
        }
  
        var forms = $('.item'); // Get all the forms
        // Update the total number of forms (1 less than before)
        $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
        var i = 0;
        // Go through the forms and set their indices, names and IDs
        for (formCount = forms.length; i &lt; formCount; i++) {
            $(forms.get(i)).find('.formset-field').each(function () {
                updateElementIndex(this, prefix, i);
            });
        }
    } // End if
    console.log('yes was removed')
  
    return false;
    }
  
    $(&quot;body&quot;).on('click', '.remove-form-row',function () {
     deleteForm($(this), String($('.add-form-row').attr('id')));
    });
  
    $(&quot;body&quot;).on('click', '.add-form-row',function () {
    return addForm($(this), String($(this).attr('id')));
   });
  </code></pre>
  <p>The problem:</p>
  <p>The problem is creating product and in Add Product FormSet it creates just one. I want to create as more adding</p>