1.建立Form
forms.py ==>
#在Flask-WTF 0.13版本,引入的表單類別為FlaskForm
#在WTForms 3.0版本,驗證函數Required變為DataRequired
from flask_wtf import FlaskForm
# 欄位定義從wtforms來
from wtforms import StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import Required,Length,Email,Regexp,EqualTo
from wtforms import ValidationError
# 繼承FlaskForm
class LoginForm(FlaskForm):
# 透過validators驗證表單POST過來的資料
username = StringField('Username',validators=[Required(),Length(1,64)])
password = PasswordField('Password',validators=[Required()])
remember_me = BooleanField('記住我')
submit = SubmitField('Log in')
# 可自定義驗證函數,以validate_field的模式定義,像這個範例就會去驗證是否有重複的username
def validate_username(self, field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('重複的使用者!')
main.py ==>
from flask import Flask
app = Flask(__name__)
# 使用flask_wtf就要設置SECRET_KEY
app.config('SECRET_KEY') = 'your key values'
@app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
#post request,判斷是否發送了一個表單
if form.validate_on_submit():
return jsonify({'result':'Submit Success'})
return render_template('login.html',form=form)
login.html ==>
# 透過flask-bootstrap快速渲染一個簡易的表單
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
但滿多時候,表單不想使用bootstrap,會有前端工程師負責設計美麗的畫面,這時候就可以jinja2的語法render form的欄位
login.html ==>
# 可以依照在form定義的欄位,直接render到template,並且給定一些input的屬性,例:class,id
<form class="form-horizontal" id="loginFrom" method="POST">
{{ form.csrf_token }} #也可以帶入csrf_token
{{form.userName(class="form-control",placeholder="Username")}}
{{form.password(class="form-control",placeholder="Password")}}
{{form.submit(class="btn btn-primary btn-block")}}
</form>