Djangodefclean()函數(shù)如何對(duì)表單中數(shù)據(jù)進(jìn)行驗(yàn)證-創(chuàng)新互聯(lián)
創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買(mǎi)多久送多久,劃算不套路!
最近寫(xiě)的資源策略管理,在ceilometer 中創(chuàng)建alarm時(shí),name要求是不能重復(fù)的,所以在創(chuàng)建policy的時(shí)候,要對(duì)policy的name字段進(jìn)行驗(yàn)證,而django中正好擁有強(qiáng)大的表單數(shù)據(jù)驗(yàn)證的功能。
#這是policy中的name字段,在表單的數(shù)據(jù)進(jìn)行提交的時(shí)候,所有的數(shù)據(jù)流會(huì)經(jīng)過(guò)clean()這個(gè)函數(shù)
name = forms.CharField(max_length=255, label=_("Name"))
#在clean函數(shù)中先取出表單中的name字段,在從數(shù)據(jù)庫(kù)里面拿到所有的數(shù)據(jù)進(jìn)行檢查 def clean(self): cleaned_data = super(CreatePolicyForm, self).clean() name = cleaned_data.get('name') try: policys = api.nova.policy_list(self.request) except: exceptions.handle(request, _('Unable to retrieve policys list.')) if policys is not None and name is not None: for policy in policys: if policy.name.lower() == name.lower(): raise forms.ValidationError( _('The name "%s" is already used by another policy.') % name ) return cleaned_data
分享標(biāo)題:Djangodefclean()函數(shù)如何對(duì)表單中數(shù)據(jù)進(jìn)行驗(yàn)證-創(chuàng)新互聯(lián)
URL地址:http://www.xueling.net.cn/article/gphso.html