wtforms的简单示例
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文件:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 {#<form method="post" action="/register">#} 9 {# <input type="text" name="username">#} 10 {# <input type="password" name="password">#} 11 {# <input type="password" name="confirm">#} 12 {# <input name="email" type="email">#} 13 {# <input type="submit">#} 14 15 {#</form>#} 16 17 {#{% load wtforms %}#} 18 <form method="POST" action="/register"> 19 <div> 20 {{ form.username.label }}: 21 {{ form.username(class="css_class") }} 22 </div> 23 {% if form.username.errors %} 24 <ol>{% for error in form.username.errors %}<li>{{ error }}</li>{% endfor %}</ol> 25 {% endif %} 26 <input type="submit"> 27 28 29 30 31 {# <div>#} 32 {# {{ form.password.label }}:#} 33 {# {{ form.password }}#} 34 {# </div>#} 35 </form> 36 37 </body> 38 </html>
3、调用:
1 @APP.route('/register', methods=['GET', 'POST']) 2 def register(): 3 form = RegistrationForm(request.form) 4 if request.method == 'POST' and form.validate(): 5 # user = User(form.username.data, form.email.data, 6 # form.password.data) 7 # db_session.add(user) 8 # flash('Thanks for registering') 9 return 'ok' 10 # return redirect(url_for('login')) 11 return render_template('register.html', form=form)
4、效果: