Reputation: 1623
There seem to be a lot of questions out there on this topic, but I haven't been able to find anything that has solved this problem for me. I am trying to make a view to create Recipe
object, which has foreign key sets for Ingredient
s and Instruction
s. When I try to submit, the formsets give me the error 'recipe': [u'The inline foreign key did not match the parent instance primary key.']
. Here's my complete view:
def recipe_add(request):
profile = profile_from_request(request)
if request.method == 'POST':
recipe_form = RecipeForm(request.POST)
if recipe_form.is_valid():
recipe = recipe_form.save(commit=False)
recipe.user = profile_from_request(request)
ingredient_form = IngredientFormSet(request.POST, prefix='ingredient', instance=recipe)
instruction_form = InstructionFormSet(request.POST, prefix='instruction', instance=recipe)
if ingredient_form.is_valid() and instruction_form.is_valid():
recipe = recipe.save()
ingredient_form.save()
instruction_form.save()
messages.success(request, _("Recipe added."))
return HttpResponseRedirect(reverse("recipes:recipe_list"))
else: # GET
recipe_form = RecipeForm()
ingredient_form = IngredientFormSet(prefix='ingredient', instance=Recipe())
instruction_form = InstructionFormSet(prefix='instruction', instance=Recipe())
return render(
request, 'recipes/recipe_add.html',
{
'profile': profile,
'recipe_form': recipe_form,
'ingredient_form': ingredient_form,
'instruction_form': instruction_form,
}
)
I'm not sure if the issue comes from creating the formsets in the GET
or POST
methods. I've tried messing with the instance
argument in both but haven't gotten anything to work.
Upvotes: 3
Views: 2231
Reputation: 1466
I had a similar issue because I forgot to add the management form for my formset in my template.
In your templates, you must have something like this :
{{ ingredient.management_form }}
{{ instruction.management_form }}
Quick way to verify is to inspect your form code in your browser and look for the hidden fields that this management form is rendering into.
You can then see if the foreign key value of those formsets matches the recipe primary key which may point you in the right direction.
Upvotes: 1