如何验证django ModelForm中的空白区域

时间:2013-05-21 12:32:31

标签: django django-models django-forms django-admin

forms.py

class PhoneForm(forms.ModelForm):
    class Meta:
        model = Phone_info
        fields = ['name1','number1','name2','number2','name3','number3','emergency','emergency_number']

我需要验证以下字段:name1,name2,name3,emergency表示空格。我在单clean()方法中进行的其他验证。如何验证空白区域?

1 个答案:

答案 0 :(得分:2)

您可以为表单上的每个字段编写自定义清理方法:

class PhoneForm(forms.ModelForm):
    class Meta:
        model = Phone_info
        fields = [
            'name1','number1','name2',
            'number2','name3','number3',
            'emergency','emergency_number'
        ]

    def clean_name1(self):
        name1 = self.cleaned_data['name1']
        if ' ' in name1:
            raise forms.ValidationError('name1 should not contain any space')
        return name1