使用模板获取错误信息
1、index.html
<form action="" method="post">
<table>
<tbody>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>重复密码:</td>
<td><input type="password" name="repassword"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="立即注册"></td>
</tr>
</tbody>
</table>
</form>
{% for error in form.username.errors %}
<p>{{ error }}</p>
{% endfor %}
{% for error in form.password.errors %}
<p>{{ error }}</p>
{% endfor %}
{% for error in form.repassword.errors %}
<p>{{ error }}</p>
{% endfor %}
2、app.py
from flask import Flask, render_template, request
from wtforms import Form, StringField, PasswordField
from wtforms.validators import Length, EqualTo
class RegForm(Form):
username = StringField(validators=[
Length(min=6, max=12, message='用户名需要输入6到12个字符')
])
password = PasswordField(validators=[
Length(min=6, max=12, message='密码需要输入6到12个字符')
])
repassword = PasswordField(validators=[
EqualTo('password', message='两次输入的密码需要相同')
])
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
form = RegForm(request.form)
if request.method == 'GET':
return render_template('index.html', form=form)
else:
if form.validate():
return '注册成功'
else:
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run()