wtformsで簡単な入力フォームを作る

はじめに

wtformsを使って簡単な入力フォームを作る方法をメモしておく。

フォルダ構成

FORM_TEST
  ├─templates
  │  ├─regist_user.html
  │  └─show_user.html
  └─app.py

コード

app.py

from flask import Flask, render_template, request, session
from wtforms import Form
from wtforms import StringField, IntegerField, SubmitField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mykey'

class UserForm(Form):
    name = StringField('名前:')
    age = IntegerField('年齢:')
    submit = SubmitField('送信')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = UserForm(request.form)

    # 登録フォームを表示
    if(request.method == "GET"):
        return render_template('regist_user.html', form=form)

    # 登録完了を表示
    elif(request.method == "POST"):
        session['name'] = form.name.data
        session['age'] = form.age.data
        return render_template('show_user.html')

if __name__ == '__main__':
    app.run(debug=True)

regist_user.html

<!DOCTYPE html>
<html lang="'ja">
    <head>
        <meta charset="utf-8">
        <title>regist_user</title>
    </head>
    <body>
        <form method="POST">
            {{ form.csrf_token }}
            {{ form.name.label }}{{ form.name() }}  <br>
            {{ form.age.label }}{{ form.age() }}    <br>
            {{ form.submit }}
        </form>
    </body>
</html>

show_user

<!DOCTYPE html>
<html lang="'ja">
    <head>
        <meta charset="utf-8">
        <title>show_user</title>
    </head>
    <body>
        <h1>Thank you for regist</h1>
        <ul>
            <li>名前: {{session['name']}}</li>
            <li>年齢: {{session['age']}}</li>
        </ul>
    </body>
</html>