问题描述
我正在处理一个 Django 项目,但在验证父表单时找不到验证 inlineformset_factory
的方法。它的 master/detail
表单方法 SaleMSTForm
是来自 SaleMST
模型的父模型表单,而 SaleDTLForm
是来自 SaleDTL
模型的详细表单。当我提交表单时,父表单工作正常并显示它应该在验证时显示的错误,但表单集不显示任何错误,并且在提交错误后被重置。另外,即使发生错误,我也想保存两个表单,不应保存父表单。这是我的代码:
models.py
class SaleMST(models.Model):
customer = models.ForeignKey(Customer,on_delete=models.RESTRICT)
date = models.DateField()
desc = models.CharField(max_length=200,blank=True)
disc = models.DecimalField(max_digits=20,decimal_places=2,blank=True)
created_by = models.CharField(max_length=20,null=True,blank=True)
created_at = models.DateTimeField(auto_Now_add=True)
modified_by = models.CharField(max_length=20,blank=True)
modified_at = models.DateTimeField(auto_Now=True)
def __str__(self):
return self.desc
class SaleDTL(models.Model):
mst = models.ForeignKey(SaleMST,on_delete=models.RESTRICT)
product = models.ForeignKey(Product,on_delete=models.RESTRICT)
desc = models.CharField(max_length=200,blank=True)
qty = models.IntegerField()
def __str__(self):
return self.desc
forms.py
class SaleMSTForm(forms.ModelForm):
class Meta:
model = SaleMST
fields = ['customer','date','desc','disc']
widgets = {
'customer': forms.Select(attrs={
'class': 'form-control'
}),'date': forms.DateInput(attrs={
'class': 'form-control','type': 'date'
}),'desc': forms.TextInput(attrs={
'class': 'form-control'
}),'disc': forms.TextInput(attrs={
'class': 'form-control'
}),}
labels = {
'customer': 'Customer','desc': 'Description','disc': 'discount'
}
class SaleForm(forms.ModelForm):
class Meta:
model = SaleDTL
fields = ['mst','product','qty']
widgets = {
'product': forms.Select(attrs={
'class': 'form-control','required': True
}),'qty': forms.TextInput(attrs={
'class': 'form-control','required': True
})
}
labels = {
'product': 'Select Product','desc': 'Description'
}
views.py
def sale(request):
m_form = SaleMSTForm()
# d_form = SaleDTLForm
d_form = inlineformset_factory(SaleMST,SaleDTL,SaleForm,extra=3)
if request.method == 'POST':
print('Printing POST: ',request.POST)
m_form = SaleMSTForm(request.POST)
if m_form.is_valid():
modal_instance = m_form.save(commit=False)
mst = modal_instance.pk
print(mst)
mstf = SaleMST.objects.get(id=mst)
msg = 'Invoice #' + str(mst) + ' has been created successfuly!'
formset = d_form(request.POST,instance=mstf)
if formset.is_valid():
# formset.save(commit=False)
formset.save()
sweetify.success(request,'Success',text=msg,persistent='OK')
return redirect('sale')
context = {
'm_form': m_form,'d_form': d_form,}
return render(request,'core/sale_form.html',context)
为了避免进一步的复杂化,我使用了默认的 Django 表单 API,以下是我在 sale_form.html 模板文件中实现它的方法:
<form class="form" method="POST" action="">
{% csrf_token %}
{{ m_form }}
<hr>
{{ d_form }}
<hr>
<input type="submit" class="btn btn-dark">
</form>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)