Django在空IntegerField上进行表单验证

时间:2012-03-31 19:30:00

标签: django django-forms django-validation

我有一个表单,我不会将其作为HTML页面的一部分呈现,但验证输入:

class milestone_form(forms.Form):
    name = forms.CharField(required=True)
    completion = forms.IntegerField(initial=0, required=False)
    due_date = forms.DateField(required=True,input_formats={'%d.%m.%Y'})
    phase = forms.IntegerField(required=True)

这个完成位导致了很多问题:

form = milestone_form(request.POST)
form.is_valid()#will return False on empty completion

我尝试覆盖form的clean(),使其为空时完成= 0:

def clean(self):
    cleaned_data = self.cleaned_data
    if cleaned_data.get('completion') is None:
        cleaned_data['completion'] = 0
    return cleaned_data 

然而,它没有帮助。还有其他我想念的东西吗?

1 个答案:

答案 0 :(得分:3)

这可能是我为空字段返回一个整数的方法,错误检查:

from django.forms import ValidationError

def clean_completion(self):
    if self.cleaned_data.get('completion'):
        try:
            return int(self.cleaned_data['completion'].strip())
        except ValueError:
            raise ValidationError("Invalid number")
    return 0