亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

禁止 save() 以防止由于未保存的相關對象“employee”而導致數據丟失

禁止 save() 以防止由于未保存的相關對象“employee”而導致數據丟失

海綿寶寶撒 2023-09-19 17:24:53
我正在研究 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條經驗 獲得超5個贊

問題解決了!

添加實例=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')



查看完整回答
反對 回復 2023-09-19
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號