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

Django中使用def clean()函数对表单中的数据进行验证

2016-08-19 10:17 645 查看
最近写的资源策略管理,在ceilometer 中创建alarm时,name要求是不能重复的,所以在创建policy的时候,要对policy的name字段进行验证,而django中正好拥有强大的表单数据验证的功能。

#这是policy中的name字段,在表单的数据进行提交的时候,所有的数据流会经过clean()这个函数
name = forms.CharField(max_length=255, label=_("Name"))


#在clean函数中先取出表单中的name字段,在从数据库里面拿到所有的数据进行检查

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐