Flask - POST Error 405 Method Not Allowed

PythonHttpPostFlask

Python Problem Overview


I'm just starting to learn Flask, and I am trying to create a form which will allow a POST method.

Here's my method:

@app.route('/template', methods=['GET', 'POST'])
def template():
    if request.method == 'POST':
        return("Hello")
    return render_template('index.html')

And my index.html:

<html>

<head>
  <title> Title </title>
</head>

<body>
  Enter Python to execute:
  <form action="/" method="post">
    <input type="text" name="expression" />
    <input type="submit" value="Execute" />
  </form>
</body>

</html>

Loading the form (rendering it when it receives GET) works fine. When I click on the submit button however, I get a POST 405 error Method Not Allowed.

Why isn't it displaying "Hello"?

Python Solutions


Solution 1 - Python

Your form is submitting to / when the method is routed for /template unless that is a typo, you should adjust your form's action attribute to point at the template view: action="{{ url_for('template') }}"

Solution 2 - Python

Replace:

 <form action="/" method="post">

with:

 <form action="{{ url_for('template') }}" method="post">

Solution 3 - Python

If you omit the action attribute, the form will post to the current URL.

Replace:

<form action="/" method="post">

with:

<form method="post">

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondarkskyView Question on Stackoverflow
Solution 1 - PythonBurhan KhalidView Answer on Stackoverflow
Solution 2 - PythonthikonomView Answer on Stackoverflow
Solution 3 - PythonAnkur_JattView Answer on Stackoverflow