Flask-sending-form-data-to-template

提供:Dev Guides
移動先:案内検索

Flask –フォームデータをテンプレートに送信

httpメソッドがURLルールで指定できることはすでに見ました。 トリガーされた関数によって受信された Form データは、それを辞書オブジェクトの形式で収集し、テンプレートに転送して、対応するWebページでレンダリングできます。

次の例では、 ‘/’ URLはフォームを持つWebページ(studentl)をレンダリングします。 入力されたデータは* result()関数をトリガーする *’/result’ URLに投稿されます。

  • results()関数は、辞書オブジェクトの *request.form に存在するフォームデータを収集し、レンダリングするために resultl に送信します。

このテンプレートは、*フォーム*データのHTMLテーブルを動的にレンダリングします。

以下は、アプリケーションのPythonコードです-

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('studentl')

@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("resultl",result = result)

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

以下は studentl のHTMLスクリプトです。

<html>
   <body>
      <form action = "http://localhost:5000/result" method = "POST">
         <p>Name <input type = "text" name = "Name"/></p>
         <p>Physics <input type = "text" name = "Physics"/></p>
         <p>Chemistry <input type = "text" name = "chemistry"/></p>
         <p>Maths <input type ="text" name = "Mathematics"/></p>
         <p><input type = "submit" value = "submit"/></p>
      </form>
   </body>
</html>

テンプレート*(resultl)*のコードを以下に示します-

<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

Pythonスクリプトを実行し、ブラウザーにURL http://localhost:5000/ を入力します。

マークを送信

[送信]ボタンをクリックすると、フォームデータがHTMLテーブルの形式で*結果*にレンダリングされます。

マーク表