pythonflask

Flask route returns “405 Method Not Allowed” on form submission



app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit')
def submit():
    username = request.form.get('username')
    return f'Hello, {username}!'

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

I get a 405 Method Not Allowed error for the /submit endpoint when I try to submit a POST request to that endpoint.

Why am I getting a 405, and how can I fix my route so it accepts POST submissions?


Solution

  • In Flask, it will only accept GET if you don't specify a method. When you submit your form with method="post", Flask sees no handler for POST on /submit and raises a 405. Add the methods argument to the decorator.

    @app.route('/submit', methods=['POST'])
    def submit():
        username = request.form.get('username')