如何在提交前检查表单集的有效性?

2024-03-29 13:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何检查表单集的有效性
让我解释一下我的情况。我有五个表格,它们包含在一个表格集中。每个表格代表一场排球比赛的一组(一场排球比赛分5组进行)
如果已经有三个代表胜利的表格,我希望能够提交我的表格集,因为如果我有第一队赢得的前三盘,第四盘和第五盘是无用的,当有三盘获胜时,比赛就结束了
我不知道我是否很清楚

您可以在下面找到我的forms.py下吼:

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")

        if cleaned_data.get("match") is not None:
            sport = cleaned_data.get("match").phase.tournament.sport

            if scoreTeam1 and scoreTeam2:
                if scoreTeam1 == scoreTeam2:
                    raise forms.ValidationError("Scores can't be equal")
                if scoreTeam1 > sport.nbPointPerSet or scoreTeam2 > sport.nbPointPerSet or (scoreTeam1 < sport.nbPointPerSet and scoreTeam2 < sport.nbPointPerSet):
                    raise forms.ValidationError("A set is played in " + str(sport.nbPointPerSet) + "points.")
                return cleaned_data
MatchSetFormset = forms.inlineformset_factory(Match, Set, form=SetUpdateForm, min_num=1, extra=0, can_delete=False)

我正在使用Django 2.2和Python 3.7.3


Tags: pydatagetifmatchformsclass表格