<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div align="center">
<h1>User Management</h1>
<form method="post">
<input type="text" name="username" placeholder="username" />
<br>
<input type="password" name="password" placeholder="password" />
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
</body>
</html>
使用html实现的表单:
用flask实现相同功能的表单:
# -*- coding:utf-8 -*-
from flask import Flask, request, render_template, redirect
from wtforms import Form, TextField, PasswordField, validators
app = Flask(__name__)
class LoginForm(Form):
# validators指定一个由验证函数组成的列表
# 在接受用户提交的数据之前验证数据
# 验证函数Required()确保提交的字段不为空
username = TextField("username", [validators.Required()])
password = PasswordField("password", [validators.Required()])
# 定义user路由
@app.route("/user", methods=['GET', 'POST'])
def login():
myForm = LoginForm(request.form)
if request.method == 'POST':
# username = request.form['username']使用request获取数据
# password = request.form['password']
# 也可以使用类实例里的表单方法来获取相应的数据
# validate来验证输入的表单数据是否有效
if myForm.username.data == "loli" and myForm.password.data == "520" and myForm.validate():
return redirect("http://www.baidu.com")
else:
message = "Login Failed"
return render_template("form1.html", message=message, form=myForm)
return render_template("form1.html", form=myForm)
if __name__ == '__main__':
app.run()
form1模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div align="center">
<h1>User Management</h1>
<form method="post">
{% if message %}
{{ message }}
{% endif %}
<br>
{{ form.username }}
<br>
{{ form.password }}
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
</body>
</html>
一样的效果图。
在WTForm3.0中Textfield被移除,使用Stringfield代替。
WTForm主要在flask中用于验证表单。
参考官方文档:http://dormousehole.readthedocs.io/en/latest/patterns/wtforms.html