【发布时间】:2019-05-09 08:40:47
【问题描述】:
我有一个包含 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 方法中的类别字段?
【问题讨论】:
-
仅在字段不是无时验证。
if nbTeamPerPool and nbTeamPerPool < 3 or nbTeamPerPool > 4: -
或者更简单,
if nbTeamPerPool not in (None, 3, 4)
标签: django forms validation