【问题标题】:Django inline formset: The inline foreign key did not match the parent instance primary keyDjango内联表单集:内联外键与父实例主键不匹配
【发布时间】: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,
        }
    )

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

【问题讨论】:

    标签: django django-forms formset inline-formset


    【解决方案1】:

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

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

    {{ ingredient.management_form }}
    
    {{ instruction.management_form }}
    

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

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

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2019-05-15
      • 1970-01-01
      相关资源
      最近更新 更多