For saving foreign keys to the model in the same view you often see:
form_obj = form.save()
form2_obj = form2.save(commit=False)
form2_obj.foreign_key = form_obj
But for formsets where you loop through each form, you are saving the form1 object multiple times (does this do anything?) and there could be an a form that is not valid some way through the loop.
Unless there is something i'm missing, the solutions i've come up with is to either do all the validity checking first, then go through the formset again once you make sure everything is valid (need to go through twice) or to save the form1 object after you make sure that is valid but delete it if you come across something in the formset that is invalid.
From the comment by @karthikr i see where i was going wrong. I originally thought you had to validate each form in a formset individually, but
formset.is_valid() covers each form so as long as you save the form after all formset checks then it should be okay.
if form1.is_valid(): if formset.is_valid(): form1_obj = form1.save() for form in formset: form_obj = form.save(commit=False) form_obj.foreign_key = form1_obj form_obj.save()