您的位置:首页 > 编程语言 > Go语言

django form系统一点需要注意的地方

2012-05-15 19:25 393 查看
学习文章: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_image_url(self):
url=self.cleaned_data['image_url']
if not endsWith(url,'.jpg','.png','.gif'):
raise forms.ValidationError('图片格式必须为jpg,png 或gif')
return url
~


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

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

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

现总结如下:

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

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

本文出自 “YEELONⒼ ” 博客,请务必保留此出处http://yeelone.blog.51cto.com/1476571/864164
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: