Flask系列09--Flask中WTForms插件,及自定义验证器

时间:2022-10-24 19:04:05

一.概述

  django中的forms组件非常的方便,在flask中有WTForms的组件实现的也是类似的功能, 安装这个插件

Flask系列09--Flask中WTForms插件,及自定义验证器

二.简单使用

  文档地址https://wtforms.readthedocs.io/en/latest/

  简单写一个注册的form

# 注册表单
class RegForm(Form):
username = simple.StringField(
label='用户名',
validators=[validators.DataRequired(message='用户名不能为空')] ) password = simple.PasswordField(
label='密码',
validators=[
validators.DataRequired(message='密码不能为空'),
validators.Length(min=1, max=10, message='密码长度不正确'),
]
) re_password = simple.PasswordField(
label='确认密码',
validators=[
validators.EqualTo('password', message='密码不一致')
]
) email = simple.StringField(
label='邮箱',
validators=[
validators.Email(message='邮箱格式不正确')
]
) hobby = core.SelectMultipleField(
label='爱好',
choices=[
(1, '足球'),
(2, '篮球'),
(3, '网球'),
], default=[1, 3], # 设置默认值,
coerce=int ) gender = core.SelectField(
label='性别',
choices=[
(1, '男'),
(2, '女')
],
default=,
coerce=int
) sub = simple.SubmitField(
label='提交',
render_kw={'style': "color: red"},
)

这里写了sub按钮,在前端文件中如果不想让标签显示出来比如Flask系列09--Flask中WTForms插件,及自定义验证器

前端页面可以这样写

<form action="" method="post" novalidate>
{% for field in form_obj %}
{% if field.type == "SubmitField" %}
<p>{{ field }}{{ field.errors.0 }}</p>
{% else %}
<p>{{ field.label }}{{ field }}{{ field.errors.0 }}</p>
{% endif %}
{% endfor %}
</form>

结果预览:

Flask系列09--Flask中WTForms插件,及自定义验证器

三 . 自定义验证器 validator

  有两种写法,一种是类的,另外一种是写成函数

1.函数

class SignupForm(Form):
age = IntegerField(u'Age')
def validate_age(form, field):
if field.data < 13:
raise ValidationError("We're sorry, you must be 13 or older to register")

2. 类

# 自定义验证器,类 的写法
class pwd_validator():
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
pwd = field.data
if pwd != '':
raise ValidationError(self.message)

示例 登陆:

# 自定义验证器,类 的写法
class pwd_validator():
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
pwd = field.data
if pwd != '':
raise ValidationError(self.message) class LoginForm(Form):
username = simple.StringField(
label='用户名',
validators=[validators.DataRequired(message='用户名不能为空'), ]
)
# 自定义验证器, 函数的写法
def validate_username(form, field):
if field.data != 'tom':
raise ValidationError('用户名错误')
password = simple.PasswordField(
label='密码',
validators=[
validators.DataRequired(message='密码不能为空'),
validators.Length(min=1, max=10, message='密码长度不正确'),
pwd_validator('密码必须是123'), ]
)
sub = simple.SubmitField(
label='登陆',
render_kw={'class': 'red'}
)

cbv中运用

class Login(views.MethodView):
def get(self):
form_obj = LoginForm()
return render_template("login.html", form_obj=form_obj)
def post(self):
dic = request.form.to_dict()
username = dic.get('username')
password = dic.get('password')
# if username == 'tom' and password == '123':
login_data = LoginForm(request.form)
if login_data.validate():
# print(login_data.data)
session['user'] = dic['username']
s = session.get('user')
return '登陆成功 session是{}'.format(s)
else: return render_template('login.html', form_obj=login_data)

Flask系列09--Flask中WTForms插件,及自定义验证器