如何检查IntegerField的验证?

时间:2019-05-09 08:40:47

标签: django forms validation

我有一个具有IntegerField的表单,该字段不是必需的。提交表单时,我想检查此字段是否正确填写。唯一接受的值为3、4或一个空字段。

forms.py

class PhaseCreationForm(forms.ModelForm):
    typePhase               = forms.CharField(label='Type of phase', widget=forms.TextInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the type of the phase'}))
    nbTeamPerPool           = forms.IntegerField(label='Number of teams per pool', required=False, widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'3 or 4'}))
    nbTeamQualified         = forms.IntegerField(label='Number of qualified', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the number of qualified'}))
    category                = MyModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={
                                    'class':'form-control'}))
    class Meta:
        model = Phase
        fields = [
            'typePhase',
            'nbTeamPerPool',
            'nbTeamQualified',
            'category',
        ]

def clean_nbTeamPerPool(self, *args, **kwargs):
        nbTeamPerPool = self.cleaned_data.get("nbTeamPerPool")
        if nbTeamPerPool < 3 or nbTeamPerPool > 4:
            raise forms.ValidationError("The number of team per pool is between 3 and 4. Please try again.")
        return nbTeamPerPool

当该字段为空时,出现此错误

  

'<'在'NoneType'和'int'的实例之间不支持

我理解此错误,我无法将None与整数进行比较,所以我的问题是如何将None与整数进行比较,或者您可以为我提出一种使空字段被接受的解决方案?

编辑: 现在我还有另一个问题。如您所见,我的表单有一个“类别”字段,这是“类别”模型的外键,我想知道如何访问 clean 方法?

1 个答案:

答案 0 :(得分:0)

先检查是否有任何值,然后进行验证:

def clean_nbTeamPerPool(self, *args, **kwargs):
    nbTeamPerPool = self.cleaned_data.get("nbTeamPerPool")
    if nbTeamPerPool:
            if nbTeamPerPool < 3 or nbTeamPerPool > 4:
                raise forms.ValidationError("The number of team per pool is between 3 and 4. Please try again.")
    return nbTeamPerPool