Why does my Flask route return a 405 error when I submit a form? #5773
-
I'm using Flask and trying to handle a form submission with POST, but I keep getting a 405 Method Not Allowed error. Here's the basic code: from flask import Flask, request
app = Flask(__name__)
@app.route("/submit")
def submit():
if request.method == "POST":
name = request.form["name"]
return f"Hello, {name}!"
return "Invalid method" I submit the form from an HTML page using method="POST", but Flask still returns a 405. What am I doing wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Because you need |
Beta Was this translation helpful? Give feedback.
-
Great question! The issue is that your route is only set to accept GET requests by default, since you didn’t specify the allowed methods. To fix the 405 error, you need to explicitly allow @app.route("/submit", methods=["GET", "POST"])
def submit():
if request.method == "POST":
name = request.form["name"]
return f"Hello, {name}!"
return "Invalid method"
This tells Flask to accept both GET and POST requests on that route. Let me know if it works! ✅ |
Beta Was this translation helpful? Give feedback.
Great question!
The issue is that your route is only set to accept GET requests by default, since you didn’t specify the allowed methods.
To fix the 405 error, you need to explicitly allow
POST
in the route definition using themethods
parameter:Let me know if it works! ✅