学习文章:http://blog.csdn.net/thinkinside/article/details/7224747
在学习这个教程的时候,有代码如下:
- class ProductForm(forms.ModelForm):
- class Meta:
- model = Product
- # exclude = [] # uncomment this line and specify any field to exclude it from the form
- def __init__(self, *args, **kwargs):
- super(ProductForm, self).__init__(*args, **kwargs)
- def clean_price(self):
- price = self.cleaned_data['price']
- if price <=0:
- raise forms.ValidationError("价格要大于0")
- return price
- def clean_p_w_picpath_url(self):
- url=self.cleaned_data['p_w_picpath_url']
- if not endsWith(url,'.jpg','.png','.gif'):
- raise forms.ValidationError('图片格式必须为jpg,png 或gif')
- return url
- ~
在这个form.py 文件写好之后,居然就生效了,数据就开始可以验证了,可是我左看右看没有看到哪里有调用clean_price 和clean_p_w_picpath_url这两个方法。难道是我对python类的理解错了,于是google。但是没有google出来。
google到一些别的文章,发现一个特点,验证方法都是以clean 开头。于是我就尝试一下,把clean删掉,方法就没有再被调用了。
之后再次google的时候,google到了结果。
现总结如下:
Django的form表单系统,会在实例化的时候自动寻找clean开头,并且是以字段的名称结束的方法并处理验证代码。
所以我们要验证price字段,自然就是:clean_price(self)方法了。