我正在研究 inlineformset_factory。Inlineformset_factory 有两个模型(WorkExperience 和 Education)与使用外键关系的 Employee 模型相关。当我提交表单时,我收到一个值错误。错误是:save() prohibited to prevent data loss due to unsaved related object 'employee'这是我的发帖方法:def post(self, request, *args, **kwargs): form = self.form_class(request.POST) # work_form = self.work_form_class(request.POST, prefix='work_form') # education_form = self.education_form_class(request.POST, prefix='education_form') work_formset = self.work_formset_class(request.POST or None, request.FILES, prefix='work_form') education_formset = self.education_formset_class(request.POST or None, request.FILES, prefix='education_form') data = request.POST.copy() # Check form validation if form.is_valid() and work_formset.is_valid() and education_formset.is_valid(): instance = form.save() # Save work experience for work_form in work_formset: work = work_form.save(commit=False) work.employee_id = instance.id work.save() work_formset.save() # Save education experience for education_form in education_formset: education = education_form.save(commit=False) education.employee_id = instance.id education.save() education_formset.save()models.py:class Employee(models.Model): """ Create employee attributes """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) e_id = models.IntegerField(unique=True, null=True) first_name = models.CharField(max_length=128, null=True) last_name = models.CharField(max_length=128, null=True)我不知道错误在哪里。阻止 save() 的错误在哪里?
1 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
问题解决了!
添加实例=form.instance
work_formset = self.work_formset_class(request.POST or None, request.FILES, instance=form.instance, prefix='work_form') education_formset = self.education_formset_class(request.POST or None, request.FILES, instance=form.instance, prefix='education_form')
添加回答
举报
0/150
提交
取消