[Django]-Setting a foreign key on a formset on formset.save()

6👍

isn’t it supposed to be

if form.cleaned_data['answer']:
    # THIS DOESN'T WORK...  PLEASE FIX..
    question = form.save(commit=False)
    question.answered_by = person
    question.save()
👤Ashok

4👍

Ashok has the right answer – form.save returns the instance object, saved or not depending on the value of commit.

As a side issue, note that this:

    for i in range(0, formset.total_form_count()):
        form = formset.forms[i]

is much better written as this:

    for form in formset.forms:

and if for some reason you really did need that index variable, this is still better:

    for i, form in enumerate(formset.forms):

Leave a comment