我正在使用BaseModelFormSet并将其传递给视图中的modelformset_factory。在BaseModelFormSet函数内部,我重写clean()进行表单集验证以引起验证错误。问题是当我尝试用错误的数据填充表单集时,验证错误根本不显示
我尝试使用非字段错误手动在模板中进行渲染,但是没有用,并查阅了文档https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#overriding-clean-on-a-modelformset
更新:如果我故意用错误的数据填充表单,它将仅验证表单集中的第一个表单,而不验证所有表单(扩展名设置为2)
forms.py
class MyModelFormSet(BaseModelFormSet):
def clean(self):
super().clean()
if any(self.errors)
return
for form in self.forms:
debit = form.cleaned_data['debit']
if debit == 100:
raise forms.ValidationError('debit is 100!')
return debit
views.py
def postpage(request):
journalLineFormSet = modelformset_factory(journalLine,exclude=('journalNumber',),extra=2,can_delete=True,formset=MyModelFormSet,max_num=2,validate_max=True)
if request.method == 'POST':
mainform = journalForm(request.POST)
subform = journalLineFormSet(request.POST)
if mainform.is_valid() and subform.is_valid():
instances = subform.save(commit=False)
for instance in instances:
instance.save()
mainform.save()
return HttpResponseRedirect('/myacc/posted/')
else:
##linesform = linesform(queryset=journal.objects.all().none())
mainform = journalForm()
subform = journalLineFormSet(queryset=journalLine.objects.all().none()) #prefix used if you want to set a cumstom prefix to from name
return render(request,'myacc/post.html',{'mainform': mainform, 'subform': subform})