一、安装
pip3 install -i https://pypi.douban.com/simple wtforms
二、作用
1、生成HTML标签
2、form表单验证
三、示例
1、登录页面
from wtforms import Form from wtforms.fields import simple from wtforms import widgets from wtforms import validators class LoginForm(Form): name = simple.StringField( label='用户名', # 校验 validators=[ validators.DataRequired(message='用户名不能为空.'), validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d') ], widget=widgets.TextInput(), # 设置属性 render_kw={'placeholder':'请输入用户名'} ) pwd = simple.PasswordField( label='密码', validators=[ validators.DataRequired(message='密码不能为空.'), validators.Length(min=8, message='用户名长度必须大于%(min)d'), validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}", message='密码至少8个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符') ], render_kw={'placeholder':'请输入密码'} ) @app.route('/login/',methods=['GET','POST']) def login(): if request.method == "GET": form = LoginForm() return render_template('login.html',form=form) # POST form = LoginForm(formdata=request.form) if form.validate(): # print(form.data) return redirect('/index/') else: # print(form.errors) return render_template('login.html', form=form)
模板
<form method="post" novalidate> <p>{{form.name}} {{form.name.errors[0]}}</p> <p>{{form.pwd}} {{form.pwd.errors[0]}} </p> <p><input type="submit" value="提交" ></p> </form>
2、注册页面
from wtforms import Form from wtforms.fields import simple from wtforms.fields import html5 from wtforms.fields import core from wtforms import widgets from wtforms import validators class RegisterForm(Form): # text name = simple.StringField( label='用户名', validators=[ validators.DataRequired() ], widget=widgets.TextInput(), render_kw={'class': 'form-control'}, default='alex' ) # password pwd = simple.PasswordField( label='密码', validators=[ validators.DataRequired(message='密码不能为空.') ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control'} ) # password pwd_confirm = simple.PasswordField( label='重复密码', validators=[ validators.DataRequired(message='重复密码不能为空.'), validators.EqualTo('pwd', message="两次密码输入不一致") ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control'} ) # emial email = html5.EmailField( label='邮箱', validators=[ validators.DataRequired(message='邮箱不能为空.'), validators.Email(message='邮箱格式错误') ], widget=widgets.TextInput(input_type='email'), render_kw={'class': 'form-control'} ) # radio gender = core.RadioField( label='性别', choices=( (1, '男'), (2, '女'), ), coerce=int # int("1") ) # select city = core.SelectField( label='城市', choices=( ('bj', '北京'), ('sh', '上海'), ) ) # multiple select hobby = core.SelectMultipleField( label='爱好', choices=( (1, '篮球'), (2, '足球'), ), coerce=int ) # checkobx favor = core.SelectMultipleField( label='喜好', choices=( (1, '篮球'), (2, '足球'), ), widget=widgets.ListWidget(prefix_label=False), option_widget=widgets.CheckboxInput(), coerce=int, default=[1, ] ) @app.route('/register/', methods=['GET', 'POST']) def register(): if request.method == 'GET': form = RegisterForm() return render_template('register.html', form=form) form = RegisterForm(formdata=request.form) if form.validate(): print(form.data) return redirect('/index/) return render_template('register.html', form=form)
模板
<form method="post" novalidate> {% for field in form %} <p>{{field.label}}: {{field}} {{field.errors[0]}}</p> {% endfor %} <input type="submit" value="提交"> </form>
3、注册页面select选项和数据库同步更新
class UserForm(Form): city = core.SelectField( label='城市', choices=(), coerce=int ) name = simple.StringField(label='姓名') def __init__(self,*args,**kwargs): super(UserForm,self).__init__(*args,**kwargs) # pymysql 语句 self.city.choices=cursor.execute('select id,name from tb1',[],type=None)
4、编辑数据
form = UserForm(data={'name':'alex','city':3})
传递数据,设置表单的默认值