I implemented a django-form with a formset. When I create a new object it works. But I faced to a problem with editing form when I don't change formset data (only data outside formset). Formset raises errors: id requeired. If I mark formset fields to delete and then add new fields it works too. Please, explain me what's going wrong and how to solve this problem. Thanks! My formset:
IngredientsFormSet = forms.inlineformset_factory(
Recipe,
RecipeIngredientsDetails,
fields="__all__",
can_delete=True,
min_num=2,
max_num=50,
extra=0,
)
And my view-function:
def recipe_edit(request, recipe_id=None):
if recipe_id:
recipe = get_object_or_404(Recipe, id=recipe_id)
else:
recipe = Recipe()
if request.method == "POST":
form = RecipeCreateForm(data=request.POST, files=request.FILES)
formset = IngredientsFormSet(data=request.POST,
prefix=INGREDIENT_FORMSET_PREFIX)
if form.is_valid() and formset.is_valid():
recipe = form.save(commit=False)
recipe.author_id = request.user.id
recipe.save()
form.save_m2m()
formset.instance = recipe
formset.save()
return redirect(reverse_lazy("index"))
context = {"form": form, "formset": formset}
return render(request, template_name="recipe-create.html",
context=context)
form = RecipeCreateForm(instance=recipe)
formset = IngredientsFormSet(
instance=recipe,
prefix=INGREDIENT_FORMSET_PREFIX,
)
context = {
"form": form,
"formset": formset,
}
return render(request, context=context, template_name="recipe-create.html")
Update: When I set value of the hidden form-field with id="ingredient-INITIAL_FORMS" to zero the errors disappear. This value is the initial number of forms in formset, the question is how to validate them. I suppose that problems are related to the management_form feature, but what is exact?