2

我正在寻找一些关于如何对表单集进行自定义验证的建议。

这就是我现在所拥有的,它返回以下我不完全知道如何处理的错误。

Exception Value: 
'MilestoneFormFormSet' object has no attribute 'save'

表格.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,)))
4

1 回答 1

3

您的 clean 方法中有一个缩进错误 - 返回值应该在 for 循环之外。

但是不要在表单集中进行这种类型的验证。当您在表单集中验证表单时,表单集验证很有用。您正在比较每个表单中的值,因此为表单集使用自定义 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)
于 2010-11-02T20:53:51.517 回答