我有一个Recipe模型和一个Step模型,其中多个步骤通过外键链接到配方。制作可同时创建新配方和多个步骤的表单的最佳解决方案是什么?谷歌搜索后,我只找到内联表格集,但他们需要一个配方的实例(由pk找到)但当然在实践中,在生成表单之前不会保存配方,因为它们(配方及其步骤)被创建在一个请求中。有人解决了类似的问题吗?
答案 0 :(得分:1)
内联表单集确实是您想要的方式。你想要做的事情是:
def add_recipe(request):
if request.method == 'POST':
form = RecipeForm(data=request.POST)
if form.is_valid():
recipe = form.save(commit=False)
steps_formset = StepsFormSet(data=request.POST, instance=recipe)
if steps_formset.is_valid():
recipe.save()
steps_formset.save()
else:
steps_formset = StepsFormSet(data=request.POST)
else:
form = RecipeForm()
steps_formset = StepsFormSet()
return render(request, 'recipe_entry.html', {'form': form, 'steps_formset': steps_formset})