Form组件钩子自定义验证

Posted louzi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Form组件钩子自定义验证相关的知识,希望对你有一定的参考价值。

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组件钩子自定义验证的主要内容,如果未能解决你的问题,请参考以下文章

DjangoForm组件 𸗰

Django 表单(中下)- 自定义钩子进行数据验证

72django之简单验证码实现与form表单钩子函数补充

python---django中form组件(数据添加前使用自定义方法进行验证,以及源码分析)

Django 批量插入数据自定义分页器多表关系的建立及Form组件(待更新。。。)

组件分享之前端组件——用于自定义表单的前端组件form-create