1👍
✅
classroom = classroom_form.save(commit=False)
Since you have used commit=False
on the classroom form, classroom
likely doesn’t have an ID value that can be assigned to student
.
Save the classroom instance first (omit the commit=False
).
if classroom_form.is_valid() and student_formset.is_valid():
classroom = classroom_form.save(commit=False) # So you can add FK
classroom.user = request.user # exclude("user",) in forms.py so it validates
classroom.save() # put it in the database for student
for form in student_formset.forms:
student = form.save(commit=False)
student.classroom = classroom # classroom is in the database
student.save()
return HttpResponseRedirect('/')
Source:stackexchange.com