码迷,mamicode.com
首页 > 其他好文 > 详细

Form组件钩子自定义验证

时间:2018-07-25 17:46:55      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:err   cep   号码   items   mod   mode   because   use   widget   

django预留的钩子方法:

def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
if field.disabled:
value = self.get_initial_for_field(field, name)
else:
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
try:
if isinstance(field, FileField):
initial = self.get_initial_for_field(field, name)
value = field.clean(value, initial)
else:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, ‘clean_%s‘ % name):
value = getattr(self, ‘clean_%s‘ % name)()
self.cleaned_data[name] = value
except ValidationError as e:
self.add_error(name, e)

自定义钩子方法:

针对一个字段做验证的时候使用clean_%s自定义验证


def clean_username(self):

username = self.cleaned_data.get("username")
username_exist = models.UserInfo.objects.filter(username=username)
if username_exist:
self.add_error("username",ValidationError("用户名已存在"))

def clean_phone(self):
phone = self.cleaned_data.get(‘phone‘)
phone_exist = models.UserInfo.objects.filter(phone=phone)
if phone_exist:
self.add_error(‘phone‘, ValidationError("手机号码已存在"))

针对多个字段做验证的时候使用clean自定义验证

def clean(self):
pwd1 = self.cleaned_data.get(‘password‘)
pwd2 = self.cleaned_data.get(‘re_password‘)

if pwd1 == pwd2:
pass
else:
self.add_error(‘re_password‘, ValidationError(‘密码输入不一致‘))

Form组件钩子自定义验证

标签:err   cep   号码   items   mod   mode   because   use   widget   

原文地址:https://www.cnblogs.com/louzi/p/9367172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!