0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

表示データを問い合わせformに入力 → 表示データが画面に表示

Posted at

完成画面

スクリーンショット 2025-04-24 18.51.37.png

問い合わせフォームで入力されたデータ: fruit_name

app.py
 <input type="text" name="fruit_name" placeholder="フルーツ名を入力">

問い合わせformのデータを取得

app.py
input_text = request.form.get("fruit_name", "")

結果を表示用変数 "mix"に代入、代入できてなければエラー表示

app.py
if input_text in fruits:
            mix = input_text
        else:
            mix = "not found"

データ送受信 テンプレ(POSTとGET両方つかう)

app.py
@app.route("/", methods=["GET", "POST"])  
    # 処理

表示したいdataの変数と、結果表示用変数をreturnで準備

app.py
return render_template("index.html", fruits=fruits, mix=mix)

表示したいdataを、最初に定義

app.py
app = Flask(__name__)

fruits = ["ストロベリー", "メロン", "大福", "オレンジ", "パイナップル"]

htmlにdataを表示するとき、空配列"mix"をset

def index():
    mix = ""  
    
    # 処理

code 全文

app.py
from flask import Flask,render_template,request

# Flaskオブジェクトの生成
app = Flask(__name__)

fruits = ["ストロベリー", "メロン", "大福", "オレンジ", "パイナップル"]

@app.route("/", methods=["GET", "POST"])
def index():
    mix = ""  # 最初に mix を空で定義(これが重要)
    if request.method == "POST":
        input_text = request.form.get("fruit_name", "")
        if input_text in fruits:
            mix = input_text
        else:
            mix = "not found"
    return render_template("index.html", fruits=fruits, mix=mix)
run.py
from app.app import app

if __name__ == "__main__":
    app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>フルーツ検索</title>
</head>
<body>
  <h2>フルーツ一覧</h2>
  <ul>
    {% for fruit in fruits %}
      <li>{{ fruit }}</li>
    {% endfor %}
  </ul>

  <h2>問い合わせフォーム</h2>
  <form method="POST">
    <input type="text" name="fruit_name" placeholder="フルーツ名を入力">
    <input type="submit" value="送信">
  </form>
  
  <p>選ばれたフルーツ:{{ mix }}</p>
  
</body>
</html>
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?