title: Sub inline_formset django
body: <p>I'm creating a Web site to enter the prices of differents products of differents product places(restaurant, Supermarket, Drug Store)</p>
  
  <p>A user can enter many product places A product place can have many products A product place(like restaurants) can have many menus</p>
  
  <p>So I have three models : 1. The first is "ProductPlace" that has as foreignKey the website user model ("User")</p>
  
  <p>The second is "Product" that has as foreignKey the "ProductPlace" model
  The Third is "Menu"(like restaurant menu) that has also as foreignkey the "ProductPlace" model
  I created formsets associated to these three models in the "forms.py" file.</p>
  
  <pre><code>#forms.py
  
  from django import forms
  from .models import *
  from django.forms.models import inlineformset_factory, modelformset_factory
  from django.contrib.auth import get_user_model
  
  User = get_user_model()
  
  class ProductPlaceForm(forms.ModelForm):
      name = forms.CharField(label='Nom', 
                              widget=forms.TextInput(attrs={
                              'class': 'form-control',
                              'placeholder': 'Nom du point de vente'
                              }))
      num_road = forms.IntegerField(label='Numero',
                                      widget=forms.NumberInput(
                                      attrs={'class': 'form-control',
                                      'placeholder': 'Numero de la rue'}))
      name_road = forms.CharField(label='Nom de la rue', 
                                  widget=forms.TextInput(attrs={
                                  'class': 'form-control',
                                  'placeholder': 'Nom de la Rue'
                                  }))
      postal_code = forms.IntegerField(label='Code Postal',
                                      widget=forms.NumberInput(
                                      attrs={'class': 'form-control',
                                      'placeholder': 'Code Postal'}))
      city =  forms.CharField(label='Ville', 
                               widget=forms.TextInput(attrs={
                                  'class': 'form-control',
                                  'placeholder': 'Ville'
                                  }))
      country =  forms.CharField(label='Pays', 
                                  widget=forms.TextInput(attrs={
                                  'class': 'form-control',
                                  'placeholder': 'Pays'
                                  }))
  
      class Meta:
          model = ProductPlace
          fields=['name', 'num_road', 'name_road', 'postal_code', 'city', 'country']
  
  ProductPlaceFormSet = inlineformset_factory(User, ProductPlace, form=ProductPlaceForm, fields=['name', 'num_road', 'name_road',
                               'postal_code', 'city', 'country'], extra=1)
  
  
  class ProductForm(forms.ModelForm):
      name = forms.CharField(label='Nom du produit', 
                              widget=forms.TextInput(attrs={
                              'class': 'form-control',
                              'placeholder': 'Nom du point de vente'
                              }))
      price = forms.IntegerField(label='Prix du produit',
                                      widget=forms.NumberInput(
                                      attrs={'class': 'form-control',
                                      'placeholder': 'Prix du produit'}))
      class Meta:
          model = Product
          fields=['name', 'price']
  
  ProductFormSet = inlineformset_factory(
      ProductPlace, Product, form=ProductForm, fields=['name', 'price'], 
      extra=1, can_delete=True
  )       
  
  
  class MenuForm(forms.ModelForm):
      name = forms.CharField(label='Nom du menu', 
                              widget=forms.TextInput(attrs={
                              'class': 'form-control',
                              'placeholder': 'Nom du menu'
                              }))
      price = forms.IntegerField(label='Prix du menu',
                                      widget=forms.NumberInput(
                                      attrs={'class': 'form-control',
                                      'placeholder': 'Prix du menu'}))
      class Meta:
          model = Menu
          fields=['name', 'price']
  
  
  MenuFormSet = inlineformset_factory(
      ProductPlace, Menu, form=MenuForm, fields=['name', 'price'], 
      extra=1, can_delete=True
  )       
  
  
  #views.py 
  
  def create_product_place(request):
      template_name = 'product_place/place.html'
      heading_message = 'Ajouter des points de vente'
      if request.method == 'GET':
          formset = ProductPlaceFormSet()
          product_formset = ProductFormSet()
          menu_formset = MenuFormSet()
          print(product_formset)
      elif request.method == 'POST':
          formset = ProductPlaceFormSet(request.POST)
          product_formset = ProductFormSet(request.POST)
          menu_formset = MenuFormSet(request.POST)
          if formset.is_valid() and product_formset.is_valid()\
               and menu_formset.is_valid():
              for form in formset:
                  #extract infos from each form and save
                  name = form.cleaned_data.get('name')
                  num_road = form.cleaned_data.get('num_road')
                  name_road = form.cleaned_data.get('name_road')
                  postal_code = form.cleaned_data.get('postal_code')
                  city = form.cleaned_data.get('city')
                  country = form.cleaned_data.get('country')
                  for product_form in product_formset:
                      product_name = product_form.cleaned_data.get('name')
                      product_price = product_form.cleaned_data.get('price')
  
                  for menu_form in menu_formset:
                      menu_name = menu_form.cleaned_data.get('name')
                      menu_price = menu_form.cleaned_data.get('price')
  
                  #save place instance
                  if name and num_road and name_road and postal_code and city\
                      and country:
                      if product_name and product_price and menu_name and menu_price:
                          ProductPlace(name=name, num_road=num_road, name_road=name_road,
                                      postal_code=postal_code,
                                      city=city, country=country, acquired_by=request.user).save()
  
                          product_place = ProductPlace.objects.get(name=name)
                          Product(name=product_name, price=product_price, place=product_place).save()
  
                          Menu(name=menu_name, price=menu_price, place=product_place).save()
  
                  return redirect('index')
      return render(request, template_name, {
          'formset': formset,
          'product_formset': product_formset,
          'menu_formset': menu_formset,
          'heading': heading_message,
      })
  
  #place.html
  
  {% extends "src/base.html" %}
  {% block body_block %}
  {% load static %}
  
  &lt;link rel="stylesheet" type="text/css" href="{% static 'product_place/place-input-style.css' %}"&gt;
  
  &lt;div class="place"&gt;
  &lt;form class="place_form" method="POST" action=""&gt;
    {% csrf_token %}
    &lt;div id="items-form-container" class="input-group"&gt;
    {{ formset.management_form }}
    &lt;h1&gt;Ajouter un point de vente&lt;/h1&gt;
     {% for  item_form in formset %}
          &lt;div id="item-{{ forloop.counter0 }}"&gt;
              {{ item_form.id }}
              {{ item_form.as_p }}
          &lt;/div&gt;
      {% endfor %}
  
      {{ product_formset.management_form }}
      &lt;h1&gt;Ajouter des produits&lt;/h1&gt;
      &lt;div class='.product'&gt;
        {% for  item_form in product_formset %}
            &lt;div id="item-{{ forloop.counter0 }}"&gt;
                {{ item_form.id }}
                {{ item_form.as_p }}
            &lt;/div&gt;
        {% endfor %}
      &lt;/div&gt;
      &lt;input type="button" value="+ Ajouter un nouveau produit" id="add_product"&gt;
  
      {{ menu_formset.management_form }}
      &lt;div class='.menu'&gt;
      &lt;h1&gt;Ajouter des menus&lt;/h1&gt;
        {% for  item_form in menu_formset %}
            &lt;div id="item-{{ forloop.counter0 }}"&gt;
                {{ item_form.id }}
                {{ item_form.as_p }}
            &lt;/div&gt;
        {% endfor %}
      &lt;/div&gt;
      &lt;input type="button" value="+ Ajouter un nouveau menu" id="add_menu"&gt;
   &lt;/div&gt;
    &lt;div class="input-group-append"&gt;
      &lt;input type="button" value="+ Ajouter un nouveau point de vente" id="add_more"&gt;
    &lt;/div&gt;
  
    &lt;div class="row spacer"&gt;
      &lt;div class="add-item"&gt;
        &lt;button type="submit" class="btn btn-block btn-primary"&gt;Créer&lt;/button&gt;
      &lt;/div&gt;
  
  &lt;div id="empty_form" style="display:none"&gt;
      &lt;br&gt; &lt;/br&gt;
      &lt;table class='no_error'&gt;
          &lt;h1&gt;Ajouter un point de vente&lt;/h1&gt;
          {{ formset.empty_form }}
      &lt;/table&gt;
  
      &lt;table class='no_error1'&gt;
          &lt;h1&gt;Ajouter des produits&lt;/h1&gt;
          {{ product_formset.empty_form }}
      &lt;/table&gt;
      &lt;input type="button" value="+ Ajouter un nouveau produit" id="add_product"&gt;
  
  
      &lt;table class='no_error1'&gt;
          &lt;h1&gt;Ajouter des menus&lt;/h1&gt;
          {{ menu_formset.empty_form }}
      &lt;/table&gt;
      &lt;input type="button" value="+ Ajouter un nouveau menu" id="add_menu"&gt;
  
  &lt;/div&gt;
  
    &lt;/div&gt;
    &lt;/form&gt;
    &lt;/div&gt;
  &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script src="{% static 'dynamic_formsets/jquery.formset.js' %}"&gt;&lt;/script&gt;
  &lt;script type='text/javascript'&gt;
        $('#add_more').click(function() {
        var form_idx = $('#id_product_places-TOTAL_FORMS').val();
        alert(form_idx)
        $('#items-form-container').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
        $('#id_product_places-TOTAL_FORMS').val(parseInt(form_idx) + 1);
        });
  
        $('#add_product').click(function() {
        var form_idx = $('#id_products-TOTAL_FORMS').val();
        alert(form_idx)
        $('.product').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
        $('#id_products-TOTAL_FORMS').val(parseInt(form_idx) + 1);
        });
  
        $('#add_menu').click(function() {
        var form_idx = $('#id_menus-TOTAL_FORMS').val();
        $('.menu').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
        $('#id_menus-TOTAL_FORMS').val(parseInt(form_idx) + 1);
        });
  &lt;/script&gt;
  
    {% comment %} &lt;script type="text/javascript"&gt;
    $('.place_form').formset({
              addText: 'add family member',
              deleteText: 'remove',
              prefix: '{{ formset.prefix }}'
            });
  &lt;/script&gt; {% endcomment %}
  {% endblock %}
  
  
  </code></pre>
  
  <p>I want to add dynamically products and menus but i can't. I can add only new product places but i can't add products or menus for a specific product place.</p>