Method Not Allowed in Flask for IntegerField form

I'm trying to set up integer field validation on a form in Flask, but I keep getting 'Method Not Allowed'. I can't see what is wrong with my routes?

My main file is:

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import IntegerField

# from perfect_numbers import classify

app = Flask(__name__)
app.config['SECRET_KEY'] = 'MySecretKey'

# num = 12
# Classify = classify(num)

class PerfectForm(FlaskForm):
    number = IntegerField(4)

@app.route('/', methods=['POST'])
def form():
    form = PerfectForm()
    return render_template('index.html', form = form)

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

Then I have a standard layout.html file:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>PERFECT App</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
  </head>
  <body>
    {% block body %}{% endblock %}
  </body>
</html>

And my index.html is:

{% extends 'layout.html' %}

{% block body %}
  <h1>PERFECT NUMBERS</h1>
  <p>This is a basic Flask App to illustrate Aliquot Sums and Perfect Numbers</p>

  <p>Input a number to check if it is abundant, perfect, or deficient</p>
  <form action="{{ url_for('/') }}" method="POST">
    {{ form.csrf_token }}
    {{ form.number }}
  </form>
  <!-- {{ num }} is {{ classify }} -->
{% endblock %}

1 answer

  • answered 2018-04-14 14:21 Aniruddh Chandratre

    First, change the app.route() signature to

    @app.route('/', methods=['POST', 'GET'])
    

    You have to fill the form and submit for your app to receive a POST request. When you first load the page on your browser, you technically send a GET request to flask, and it returns the page.

    To handle your POST request separately, do something like this :

    @app.route('/', methods=['POST', 'GET'])
    def form():
        if request.method == 'POST':
            # Do something with request (access form elements with request.get(key))
            return 'Somehing here'
        form = PerfectForm()
        return render_template('index.html', form = form)