Flask-WTF 對 WTForms 進行了封裝使它可以在 Flask 框架中能夠被調用,其中 Flask-WTF 的功能都是繼承自 WTForms ,所以安裝 Flask-WTF 時會自動安裝 WTForms 模塊。html
pip install flask-wtf
表單類能夠繼承自Flask-WTF封裝的FlaskForm類,能夠從wtforms導入表單字段的類型,以下表單類的建立:python
# -*- coding: utf-8 -*- from flask_wtf import FlaskForm from wtforms import StringField, RadioField, DateField, DecimalField, SelectField class EmployeeForm(FlaskForm): name = StringField('姓名') gender = RadioField('性別', default='男') job = StringField('職位') birthdate = DateField('出生日期') idCard = StringField('身份證號') address = StringField('地址') salary = DecimalField('工資') department = SelectField('部門')
根據建立好的表單類,咱們就能夠建立咱們的視圖函數,來處理和呈現咱們的代碼邏輯:flask
# -*- coding: utf-8 -*- from flask import render_template from flask.views import MethodView from pms.forms import EmployeeForm class EmployeeEditOrCreateView(MethodView): def get(self, id=None): form = EmployeeForm() return render_template('admin/emp-create-or-edit.html', form=form) def post(self, id=None): pass # 添加視圖函數規則,並添加視圖函數的endpoint employee.add_url_rule('/create_or_edit/<id>', view_func=EmployeeEditOrCreateView.as_view('emp_create_or_edit'))
在前臺頁面咱們就可使用咱們傳遞的表單類進行form表單控件的替換了:app
<form class="form-horizontal" role="form" method="post" action="{{ url_for('admin.emp_add') }}"> {# 姓名 #} <div class="form-group"> {# <label for="name" class="col-lg-2 col-sm-2 control-label">姓名</label>#} {# 使用flask-wtf表單控件以後,label標籤也能夠省略#} {{ form.name.label(class="col-lg-2 col-sm-2 control-label") }} <div class="col-lg-6"> {# <input type="text" class="form-control" id="name" name="name">#} {# 若是你但願某些控件的屬性也添加進來,能夠直接在name中加入,方式以下:#} {{ form.name(class="form-control") }} </div> </div> </form>
展現效果:框架
Flask-WTF 默認爲每一個表單啓用了 CSRF 保護,它會爲咱們自動生成 CSRF 令牌。在Flask-WTF 中默認狀況會使用程序密鑰對 CSRF 令牌進行簽名,因此咱們須要爲程序設置密鑰:函數
app.secret_key = 'HENjsa3IJ7HfF9KG'