我有一个表单和一个formset。 Formset包含要创建的列外键。但是我的表单没有保存,并且抛出了save() prohibited to prevent data loss due to unsaved related object
错误。我怎么能将这两个数据一起保存?
这是我的观点:
def purchaseOrderView(request):
if request.method == 'POST':
formset = POFormSet(request.POST)
form = POHeaderForm(request.POST)
print("POSTED")
if form.is_valid() and formset.is_valid():
form.save()
formset.save()
messages.success(request,"VALID SUBMISSION")
return render(request,'purchase_order.html',{'formset':formset, 'form':form})
else:
return render(request, 'purchase_order.html', {'formset': formset, 'form': form})
else:
formset = POFormSet()
form = POHeaderForm()
return render(request,'purchase_order.html',{'formset':formset, 'form':form})
这是我的模型结构:
class POHeaderModel(models.Model):
date = models.DateTimeField(blank=False, default=timezone.now)
reference = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True)
supplier = models.ForeignKey(SuppliersModel, on_delete=models.PROTECT)
note = models.CharField(validators=[alphanumeric], max_length=300, blank=True, null=True)
total = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(0)])
class POBodyModel(models.Model):
PO = models.ForeignKey(POHeaderModel, on_delete=models.PROTECT)
item_number = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True)
description = models.CharField(validators=[alphanumeric], max_length=100, blank=True, null=True)
quantity = models.IntegerField(blank=True, null=True)
rate = models.DecimalField(decimal_places=2, max_digits=10)
discount = models.DecimalField(decimal_places=2, max_digits=10,blank=True, null=True)
total = models.DecimalField(decimal_places=2, max_digits=10, blank=False)
在各种博客中有很多例子,在这里使用with transaction.atomic():
的问题。但没有一个适用或可能不适合我的情况。有什么建议吗?
答案 0 :(得分:0)
您需要通过传递来设置父对象的格式,如下所示:
formset = POFormSet(request.POST,instance=POHeaderinstance)