title: Django - making form which contains two related models
body: <p>I wonder if it is possible to make a Django model based form which will allow to create two models which one will be passed as a foreign key to second one.</p>
  <p>let we have these models:</p>
  <pre><code>class Book(models.Model):
      title = models.CharField(max_length=200)
      published = models.DateField()
      
      def __str__(self):
          return self.name
  
  class Chapter(models.Model):
      name = models.CharField(max_length=200)
      number = models.IntegerField()
      book = models.ForeignKey(Book, on_delete=models.CASCADE)
  
      def __str__(self):
          return self.name
  </code></pre>
  <p>I'd like to make a view which will contain BookForm and many ChapterForms</p>
  <p>Something like:</p>
  <pre><code>Book.title = [input]
  Book.published = [input]
  </code></pre>
  <p>and below that (still in the same view)</p>
  <pre><code>Chapter.name = [input]
  Chapter.number = [input]
  </code></pre>
  <pre><code>Chapter.name = [input]
  Chapter.number = [input]
  </code></pre>
  <pre><code>add more chapters
  </code></pre>
  <p>After submitting form, Book and related chapters should be created</p>
  <p>How can I achieve it?</p>
  <p>Till now I was just making two views:</p>
  <p>One for making a Book and second one for chapter which gets created book's id as a parameter in URL, but I'd like to make it in one view to allow user to make Book and Chapters at the same time.</p>
  <h2>Edit:</h2>
  <p>After many tries I made it. I'm not sure if it's proper way to do that but it works fine. (It's made on different models)</p>
  <p>That's my code:</p>
  <pre><code>def Recipe_create_view(request, *args, **kwargs):
  
      context = {}
      recipe = None
  
      recipe_form = RecipeForm()
      if request.method == 'POST':
          recipe_form = RecipeForm(request.POST)
          if recipe_form.is_valid():
              recipe_form.save()
              recipe = Recipe.objects.create(name=recipe_form.data['name'])
      
      IngredientFormset = inlineformset_factory(Recipe, Ingredient, fields=('name', 'quantity'), can_delete=True, extra=3, max_num=10)
      if request.method == 'POST':
          formset = IngredientFormset(request.POST, instance=recipe)
          if formset.is_valid():
              formset.save()
              id = recipe.id
              recipe_duplicate = Recipe.objects.get(id=id-1)
              recipe_duplicate.delete()
  
              return redirect('index')
      
      formset = IngredientFormset(instance=recipe)
  
      context['formset'] = formset
      context['recipe_form'] = recipe_form
      return render(request, 'recipes/create_ingredients.html', context)  
  </code></pre>