flask-wtf - Flask

Flask_WTF とは

Flask_WTF とは、フォームが簡単に作成できる Flask のライブラリ。

インストール

pip install flask-wtf

WTForms を使ってフォーム画面を構築するときに便利なフィールドとバリデータを提供するパッケージです。

インストール

pip install WTForms

フォームの作成

ディレクトリ構成

  • project
    • templates
      • index.html
      • result.html
    • app.py

app.py

from flask import Flask, render_template, url_for, redirect, session
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField

app = Flask(__name__)

# CSRF 対策のために必要
app.config['SECRET_KEY'] = 'msecretkey'

class MyForm(FlaskForm):
    msg = StringField('msg')
    submit = SubmitField()

@app.route('/', methods=["GET"])
def index():
    form = MyForm()
    return render_template('index.html', form=form)

@app.route('/', methods=["POST"])
def index_get():
    form = MyForm()
    session["msg"] = form.msg.data
    return redirect('result')

@app.route('/result', methods=["GET"])
def result_get():
    msg = session["msg"]
    return render_template('result.html', message = msg)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>flask app/index</h1>
  <form action='/' method="post">
    {{ form.hidden_tag() }}
    <p>{{ form.msg.label }} {{ form.msg() }}</p>
    <p>{{ form.submit() }}</p>
  </form>
</body>
</html>

result.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>flask app/result</h1>
  <p>{{message}}</p>
</body>
</html>

フィールド

各フィールドを定義するクラスを作成します。フォームやバリデーションについてはクラス内で設定します。

from wtforms import StringField, SubmitField

class MyForm(FlaskForm):
    msg = StringField('msg')
    submit = SubmitField()

指定できるフィールドには以下のようなものがあります。

  • BooleanField
  • DateField
  • DateTimeField
  • DateTimeLocalField
  • DecimalField
  • DecimalRangeField
  • EmailField
  • FileField
  • MultipleFileField
  • FloatField
  • IntegerField
  • IntegerRangeField
  • MonthField
  • RadioField
  • SelectField
  • SearchField
  • SelectMultipleField
  • SubmitField
  • StringField
  • TelField
  • TimeField
  • URLField
  • HiddenField
  • PasswordField
  • TextAreaField
  • ColorField