LoginSignup
3
4

More than 1 year has passed since last update.

Flask でフォームを保持する方法

Posted at

Flask でフォームを作っていて、
送信ボタンを押したときにフォームの中身が全部消えるのが嫌だったので、
対策方法をメモっておきます。

できること

Flaskでフォームを保持する方法がわかる

辞書でフォームのデータを引っ張っておく

request.formに辞書の形でフォームのデータが内包されているため、
これを次のレンダー時に引っ張ってくるようにしましょう。

from Flask import request


@app.route('/', methods=["GET", "POST"])
def index():
    if request.method == 'POST':
        # POSTの場合
        return render_template('index.html', form_data=request.form)
    else:
        # GETの場合
        return render_template('index.html')

セッションに保管しておいて、次来たときでも呼び出せるようにしておくのもいいですね。

from Flask import request,session


@app.route('/', methods=["GET", "POST"])
def index():
    for request.form in key:
        session[key]

    if request.method == 'POST':
        return render_template('index.html', form_data=session)
    else:
        return render_template('index.html')

HTML側で細工しておく

力技ですが、HTMLに{% if %}とかを入れて対処しましょう。

{% if form_data %}
<input type={{type}} class="form-control" id={{id}} name={{id}} value="{{session[id]}}">
{% else %}
<input type={{type}} class="form-control" id={{id}} name={{id}}>
{% endif%}

フォームが一つとかだけならいいんですが、同じようなフォームを複数扱う場合に大変なので、
マクロ機能を使うと大変便利です。
え?違う内容のフォームがたくさんある?…力技でどうにかしましょう

{% macro form(id) -%}
    {% if form_data %}
    <input type={{type}} class="form-control" id={{id}} name={{id}} value="{{session[id]}}">
    {% else %}
    <input type={{type}} class="form-control" id={{id}} name={{id}}>
    {% endif%}
{%- endmacro %}
3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4