1、先定义一个类:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by xxx on 2017/3/13 from wtforms import Form, BooleanField, TextField, PasswordField, validators, StringField class RegistrationForm(Form):
username = StringField('username', [validators.Length(min=4,max=10,message='长度必须在4~10之间')])
# email = StringField('email', [validators.Length(min=6, max=35)])
# password = PasswordField('password', [
# validators.DataRequired(),
# validators.EqualTo('confirm', message='Passwords must match')
# ])
# confirm = PasswordField('Repeat Password')
# accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])
2、定义html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{#<form method="post" action="/register">#}
{# <input type="text" name="username">#}
{# <input type="password" name="password">#}
{# <input type="password" name="confirm">#}
{# <input name="email" type="email">#}
{# <input type="submit">#} {#</form>#} {#{% load wtforms %}#}
<form method="POST" action="/register">
<div>
{{ form.username.label }}:
{{ form.username(class="css_class") }}
</div>
{% if form.username.errors %}
<ol>{% for error in form.username.errors %}<li>{{ error }}</li>{% endfor %}</ol>
{% endif %}
<input type="submit"> {# <div>#}
{# {{ form.password.label }}:#}
{# {{ form.password }}#}
{# </div>#}
</form> </body>
</html>
3、调用:
@APP.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
# user = User(form.username.data, form.email.data,
# form.password.data)
# db_session.add(user)
# flash('Thanks for registering')
return 'ok'
# return redirect(url_for('login'))
return render_template('register.html', form=form)
4、效果: