我正在寻找有关如何在表单集上进行自定义验证的一些建议。
这就是我现在所拥有的,它返回以下错误,我不完全知道如何处理。
Exception Value:
'MilestoneFormFormSet' object has no attribute 'save'
Forms.py
class BaseMilestoneFormSet(BaseFormSet):
def clean(self):
for form in self.forms:
data = form.cleaned_data
target_date = data["target_date"]
project = data["project"]
if target_date > project.target_date:
raise forms.ValidationError("Target Date is outside of project target date")
return data
MilestoneFormSetNew = modelformset_factory(Milestone, formset=BaseMilestoneFormSet, max_num=50, extra=1)
Views.py摘录
if request.method == 'POST': # Loop through the submitted formsets check for erros and save the data.
formsetNew = MilestoneFormSetNew(request.POST, prefix='new')
if formsetNew.is_valid():
formsetNew.save()
return HttpResponseRedirect(reverse('pooflinger.project.views.detail', args=(project.id,)))
答案 0 :(得分:3)
你的clean方法中有一个缩进错误 - 返回应该在for循环之外。
但是不要在formset中进行这种类型的验证。在表单集中的表单之间进行验证时,Formset验证非常有用。您正在比较每个表单中的值,因此将自定义ModelForm用于表单集更有意义。
class MilestoneForm(forms.ModelForm):
def clean(self):
data = self.cleaned_data
target_date = data["target_date"]
project = data["project"]
if target_date > project.target_date:
raise forms.ValidationError("Target Date is outside of project target date")
return data
MilestoneFormSetNew = modelformset_factory(Milestone, form=MilestoneForm, max_num=50, extra=1)