A. Installation
pip3 install wtforms
II. Simple to use
1. Create a flask objects
from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets
app = Flask(__name__, template_folder='templates')
app.debug = True
II. Form component generated
class LoginForm(Form):
# 字段(内部包含正则表达式)
name = simple.StringField(
label='用户名', #form表单的标签
validators=[ #过滤的一些条件
validators.DataRequired(message='用户名不能为空.'),
validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')
],
widget=widgets.TextInput(), # 页面上显示的插件
render_kw={'class': 'form-control'} #form表单页面中显示的类名
III. Routing
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
form = LoginForm() #生成form对象
return render_template('login.html', form=form) #form对象渲染
else:
form = LoginForm(formdata=request.form)
if form.validate(): #进行form校验
print('用户提交数据通过格式验证,提交的值为:', form.data)
else:
print(form.errors)
return render_template('login.html', form=form)
if __name__ == '__main__':
app.run()
IV. Page rendering
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form method="post">
<p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p>
<p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p>
<input type="submit" value="提交">
</form>
</body>
</html>
III. Related Properties
1.field field
WTForms support HTML fields:
Field Type | Explanation |
---|---|
StringField | Text field, type text equivalent type of input tag |
TextAreaField | Multi-line text fields |
PasswordField | Password text field |
HiddenField | Hidden text field |
DateField | Text fields, the format is datetime.date |
DateTimeField | Text fields, the format is datetime.datetime |
IntegerField | Text fields, an integer value |
DecimalField | A text field, the value decimal.Decimal |
FloatField | A text field, as a float |
BooleanField | Check box, a value of True and False |
RadioField | A group of radio buttons |
SelectField | drop-down list |
SelectMultipleField | Drop-down list, select a plurality of values |
FileField | File upload field |
SubmitField | Form submit button |
FormFiled | As fields are embedded in the form of another form |
FieldList | Subset of the specified type field |
2.Validators validator
WTForms can support many forms of verification functions:
Validation function | Explanation |
---|---|
Verify email address | |
EqualTo | Commonly used in the case where two input key confirmation claim; comparing values of two fields |
IPAddress | Verify IPv4 network address |
Length | Verification of the length of the input string |
NumberRange | Verification of an entered value in the digital range |
Optional | Other validation function is skipped when no value |
DataRequired | Ensure that field data |
Regexp | Use regular expressions to validate input values |
URL | Verification url |
AnyOf | Be sure to enter a value in the list of optional value |
NoneOf | Ensure that the input value is not in a selectable list |
3. field parameters
parameter name | Introduction |
---|---|
label | Field aliases, the page can show through the field .label |
validators | Validation rules list |
filters | Perchloric list, the data submitted for filtering |
description | 描述信息,通常用于生成帮助信息 |
id | 表示在form类定义时候字段的位置,通常你不需要定义它,默认会按照定义的先后顺序排序。 |
default | 默认值 |
widget | html插件,通过该插件可以覆盖默认的插件,更多通过用户自定义 |
render_kw | 自定义html属性 |
choices | 复选类型的选项 |
4.局部钩子
#在form类中
def validate_字段名(self, field):
#self.data 获得全局字段的一个类似字典的格式
#self.data['字段'],可以获得全局中任意字段
#field.data 当前字段的值
#无需返回值,如果有不满足的情况需要抛错
#如两个密码,有两种情况
# raise validators.ValidationError("密码不一致") # 继续后续验证
# raise validators.StopValidation("密码不一致") # 不再继续后续验证
5.再不改变模型情况下修改值
#在form类中
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.字段名.choices = ((1, '篮球'), (2, '足球'), (3, '羽毛球'))
四.写好的模板
from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets
app = Flask(__name__, template_folder='templates')
app.debug = True
class RegisterForm(Form):
name = simple.StringField(
label='用户名',
validators=[
validators.DataRequired()
],
widget=widgets.TextInput(),
render_kw={'class': 'form-control'},
default='cxw'
)
pwd = simple.PasswordField(
label='密码',
validators=[
validators.DataRequired(message='密码不能为空.')
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control'}
)
pwd_confirm = simple.PasswordField(
label='重复密码',
validators=[
validators.DataRequired(message='重复密码不能为空.'),
validators.EqualTo('pwd', message="两次密码输入不一致")
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control'}
)
email = html5.EmailField(
label='邮箱',
validators=[
validators.DataRequired(message='邮箱不能为空.'),
validators.Email(message='邮箱格式错误')
],
widget=widgets.TextInput(input_type='email'),
render_kw={'class': 'form-control'}
)
gender = core.RadioField(
label='性别',
choices=(
(1, '男'),
(2, '女'),
),
#这句话的意思是上面的choices元组的第一个值是int类型
#如果上上面为(‘1’, '男'),(‘2’, '女'),则下面的coerce则不用写
coerce=int # “1” “2”
)
#这里是单选框
city = core.SelectField(
label='城市',
choices=(
('bj', '北京'),
('sh', '上海'),
)
)
#这里是多选框
hobby = core.SelectMultipleField(
label='爱好',
choices=(
(1, '篮球'),
(2, '足球'),
),
coerce=int
)
#这里是多选的checkbox
favor = core.SelectMultipleField(
label='喜好',
choices=(
(1, '篮球'),
(2, '足球'),
),
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput(),
coerce=int,
default=[1, 2]
)
#这里可以改值
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.favor.choices = ((1, '篮球'), (2, '足球'), (3, '羽毛球'))
def validate_pwd_confirm(self, field):
"""
自定义pwd_confirm字段规则,例:与pwd字段是否一致
:param field:
:return:
"""
# 最开始初始化时,self.data中已经有所有的值
if field.data != self.data['pwd']:
# raise validators.ValidationError("密码不一致") # 继续后续验证
raise validators.StopValidation("密码不一致") # 不再继续后续验证
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
#这里可以传默认值
form = RegisterForm(data={'gender': 2,'hobby':[1,]}) # initial
return render_template('register.html', form=form)
else:
form = RegisterForm(formdata=request.form)
if form.validate():
print('用户提交数据通过格式验证,提交的值为:', form.data)
else:
print(form.errors)
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run()