Home > other >  Django - form making one parent object and multiple child objects
Django - form making one parent object and multiple child objects

Time:08-21

I'm trying 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.

models.py

class Recipe(models.Model):
    name = models.CharField(max_length=200)
    
    def __str__(self):
        return self.name

class Ingredient(models.Model):
    name = models.CharField(max_length=200)
    quantity = models.CharField(max_length=200)
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

forms

class IngredientForm(ModelForm):
    class Meta:
        model = Ingredient
        fields = ['name', 'quantity']

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ['name']

and views.py ---- here is the problem

def new_recipe_create_view(request, *args, **kwargs):
    context = {}
    created_recipe = None
    form = RecipeForm()
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            print("recipe successfully created")
            form.save()
            name = form.data['name']
            created_recipe = Recipe.objects.filter(name=name).last()
#new recipe is being made correctly
            
    IngredientFormSet = inlineformset_factory(Recipe, Ingredient, fields=('name', 'quantity'), extra=3, max_num=10, labels = {
            'name': (''),
            'quantity': (''),
        })

    if request.method == 'POST':
        formset = IngredientFormSet(request.POST, instance=created_recipe)
        if formset.is_valid():
            formset.save()
        else:
            print("formset is not valid") # <------------------------------------------
    else:
        formset = IngredientFormSet( instance=created_recipe)

    if form.is_valid() and formset.is_valid():
        return redirect('index')

    context['formset'] = formset
    context['form'] = form
    return render(request, 'recipes/create_recipe.html', context)   

part with inlineformset_factory, I made following docs: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#inline-formsets

chapter: Using an inline formset in a view

but it does not work --> formset.is_valid() is returning False Where is the Issue ?

CodePudding user response:

It seems like you could be missing the {{formset.management_form}} in the HTML template.

put this as a child to the form tag.

<form ...>
    {{form...}}
    {{formset..}}
    {{formset.management_form}}
</form>
  • Related