Skip to content Skip to sidebar Skip to footer

Saving Model Before Checking Validity Of Another Formset (for Foreign Key)

For saving foreign keys to the model in the same view you often see: if form1.is_valid(): if form2.is_valid(): form_obj = form.save() form2_obj = form2.save(com

Solution 1:

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()

Post a Comment for "Saving Model Before Checking Validity Of Another Formset (for Foreign Key)"