学习文章:http://blog.csdn.net/thinkinside/article/details/7224747

 在学习这个教程的时候,有代码如下:

 

  1. class ProductForm(forms.ModelForm): 
  2.  
  3.     class Meta: 
  4.         model = Product 
  5.         # exclude = [] # uncomment this line and specify any field to exclude it from the form 
  6.  
  7.     def __init__(self, *args, **kwargs): 
  8.         super(ProductForm, self).__init__(*args, **kwargs) 
  9.  
  10.     def clean_price(self): 
  11.         price = self.cleaned_data['price'] 
  12.         if price <=0: 
  13.                 raise forms.ValidationError("价格要大于0") 
  14.         return price 
  15.     def clean_p_w_picpath_url(self): 
  16.         url=self.cleaned_data['p_w_picpath_url'] 
  17.         if not endsWith(url,'.jpg','.png','.gif'): 
  18.                 raise forms.ValidationError('图片格式必须为jpg,png 或gif') 
  19.         return url 
  20. ~                           

 

在这个form.py 文件写好之后,居然就生效了,数据就开始可以验证了,可是我左看右看没有看到哪里有调用clean_price 和clean_p_w_picpath_url这两个方法。难道是我对python类的理解错了,于是google。但是没有google出来。

google到一些别的文章,发现一个特点,验证方法都是以clean 开头。于是我就尝试一下,把clean删掉,方法就没有再被调用了。

之后再次google的时候,google到了结果。

现总结如下:

Django的form表单系统,会在实例化的时候自动寻找clean开头,并且是以字段的名称结束的方法并处理验证代码。

所以我们要验证price字段,自然就是:clean_price(self)方法了。