您可以通过这种方式向 form.clean() 添加自定义行为:
class YourForm(forms.Form):
# Everything as before.
...
def clean_name(self):
data = self.cleaned_data['name']
if data.strip() == '':
raise forms.ValidationError(u"You must provide more than just whitespace.")
# Always return the cleaned data, whether you have changed it or
# not.
return data
但是,如果您想创建一种自动获得此类验证的字段,您可以添加一个像这样的新类
class NoSpacesCharField(forms.CharField):
def validate(self, value):
# Use the parent's handling of required fields, etc.
super(NoSpacesCharField, self).validate(value)
if value.strip() == '':
raise ValidationError(u"You must provide more than just whitespace.")
然后NoSpacesCharField
像通常使用 forms.CharField 一样使用。
我目前无法测试此代码,因此其中可能存在奇怪的扭结,但它应该可以帮助您完成大部分工作。有关 Django 中表单验证的更多信息,请参阅https://docs.djangoproject.com/en/dev/ref/forms/validation/