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?

Typeerror / method not allowed / bootstrap

Last updated at Posted at 2025-04-25

最初にアクセスする / が POSTのみの時

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

問題code
@app.route("/", methods=["POST"])
解決策
@app.route("/", methods=["GET", "POST"])

アクセスするのが"/"以外、 POST専用にしてもエラーにならない

@app.route("/submit", methods=["POST"])
def submit():
    if request.method == "POST":
        name = request.form["name"]
        message = request.form["message"]
        return render_template("index.html", name=name, message=message)

データが問い合わせformで送信された時だけ、ある文章を表示したい

index.html
{% if name and message %}
<h1>ありがとうございました、{{ name }}さん</h1>
<p>メッセージ: {{ message }}</p>
{% endif %}

methods=["GET", "POST"]があり、elseがない時

TypeError: The view function for 'submit' did not return a valid response. The function either returned None or ended without a return statement.
解決策
if request.method == "POST":
    return render_template("index.html", name=name)
else:
    return render_template("index.html")

いいcodeと悪いcode

悪いの
@app.route("/", methods=["GET", "POST"])
def submit():
    if request.method == "POST":
        name = request.form["name"]
        message = request.form["message"]
        return render_template("index.html", name=name, message=message)
    else:
        return render_template("index.html")
いいの
@app.route("/", methods=["GET", "POST"])
def submit():
    name = ""
    message = ""
    result = ""

    if request.method == "POST":
        name = request.form["name"]
        message = request.form["message"]

        if name and message:
            result = f"{name} / {message}"
        else:
            result = "not found"

    return render_template("index.html", name=name, message=message, result=result)

after-html
<form action="/" method="POST">
  <label for="name">名前:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="message">メッセージ:</label>
  <textarea id="message" name="message" required></textarea>
  <br>
  <input type="submit" value="送信" class="btn btn-primary">

</form>

{% if name and message %}
<p>{{ result }}</p>
{% endif %}

bootstrap 入れたい

index.html
<!DOCTYPE html>
<html>
  <head>
  <meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
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?