如何为表单集构建清洁方法?

时间:2019-05-16 11:09:32

标签: python django django-forms

我重写了表单的 clean() 方法,并且具有该表单的表单集。问题是 clean() 方法未调用,我认为验证无效,我也不知道为什么。你能帮助我吗 ?我也许(肯定)做错了什么?

forms.py

class SetUpdateForm(forms.ModelForm):

    class Meta:
        model = Set
        fields = [
            'scoreTeam1',
            'scoreTeam2',
            'match',
        ]

        def clean(self):
            cleaned_data = super().clean()
            scoreTeam1 = cleaned_data.get("scoreTeam1")
            scoreTeam2 = cleaned_data.get("scoreTeam2")
            sport = cleaned_data.get("match").phase.tournament.sport

            if scoreTeam1 and scoreTeam2:
                print("a")
                if scoreTeam1 < sport.nbPointPerSet and scoreTeam2 < sport.nbPointPerSet or scoreTeam1 > sport.nbPointPerSet and scoreTeam2 > sport.nbPointPerSet:
                    raise forms.ValidationError("A set is played in" + str(sport.nbPointPerSet) + " points")
                if scoreTeam1 == scoreTeam2:
                    raise forms.ValidationError("Scores can't be equal")
                return cleaned_data



MatchSetFormset = forms.inlineformset_factory(Match, Set, form=SetUpdateForm, min_num=1, extra=0, can_delete=False)

通常,每次验证表单时都应调用该方法吗?我不明白。

编辑:

forms.py

class SetUpdateForm(forms.ModelForm):

    class Meta:
        model = Set
        fields = [
            'scoreTeam1',
            'scoreTeam2',
            'match',
        ]

class MatchSetFormset(forms.inlineformset_factory(Match, Set, form=SetUpdateForm, min_num=1, extra=0, can_delete=False)):
    def clean(self):
        super(MatchSetFormset, self).clean()

        for form in self.forms:
            if not form.is_valid():
                continue

            scoreTeam1 = form.cleaned_data["scoreTeam1"]
            scoreTeam2 = form.cleaned_data["scoreTeam2"]
            if scoreTeam1 > form.cleaned_data["match"].phase.tournament.sport.nbPointPerSet:
                raise forms.ValidationError("error")

我尝试了这个,实际上它可以工作,但是我没有错误,为什么?

0 个答案:

没有答案