【发布时间】:2014-11-15 08:13:07
【问题描述】:
似乎有很多关于这个主题的问题,但我找不到任何可以为我解决这个问题的东西。我正在尝试创建Recipe 对象的视图,该对象具有Ingredients 和Instructions 的外键集。当我尝试提交时,表单集给了我错误'recipe': [u'The inline foreign key did not match the parent instance primary key.']。这是我的完整观点:
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,
}
)
我不确定问题是否来自在 GET 或 POST 方法中创建表单集。我已经尝试在两者中弄乱instance 参数,但没有任何工作。
【问题讨论】:
标签: django django-forms formset inline-formset