I have two models employee and child(Enfant) related by a foreignkey, like models.py
class Enfant(models.Model) : id_emp = models.ForeignKey(Employee, on_delete=models.CASCADE) id_Enfant=models.IntegerField(blank=True,primary_key=True)
views.py
form = EmployeeForm(request.POST or None) form_EnfantForm_formset =formset_factory(EnfantForm, formset=EnfantFormSet) if request.method == 'POST' if form.is_valid() : #pdb.set_trace() new_employee=form.save() EnfantForm_formset0 = form_EnfantForm_formset.save(commit=False) EnfantForm_formset0.employee= new_employee EnfantForm_formset0.save()
I need to save employee record and enfant records
Saving a formset returns a list of instances. You have to iterate over this list and assign the field:
instances = form_EnfantForm_formset.save(commit=False)
for instance in instances:
instance.employee = new_employee
instance.save()
Source: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#saving-objects-in-the-formset
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.