gpt4 book ai didi

Django 内联表单集 : The inline foreign key did not match the parent instance primary key

转载 作者:行者123 更新时间:2023-12-04 18:06:11 27 4
gpt4 key购买 nike

似乎有很多关于这个主题的问题,但我一直没能找到任何解决这个问题的方法。我正在尝试创建一个 View 来创建 Recipe 对象,该对象具有用于 IngredientInstruction 的外键集。当我尝试提交时,表单集给我错误 '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,
}
)

我不确定问题是否来自在 GETPOST 方法中创建表单集。我试过在两者中弄乱 instance 参数,但没有任何效果。

最佳答案

我遇到了类似的问题,因为我忘记在我的模板中为我的表单集添加管理表单。

在你的模板中,你必须有这样的东西:

{{ ingredient.management_form }}

{{ instruction.management_form }}

验证的快速方法是在浏览器中检查您的表单代码,并查找此管理表单呈现到的隐藏字段。

然后您可以查看这些表单集的外键值是否与配方主键匹配,这可能会为您指明正确的方向。

关于Django 内联表单集 : The inline foreign key did not match the parent instance primary key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955839/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com