Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – form making one parent object and multiple child objects

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading