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__':

Then I have a standard layout.html file:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <meta charset="utf-8">
    <title>PERFECT App</title>
    <link rel="stylesheet" href="" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    {% block body %}{% endblock %}

And my index.html is:

{% extends 'layout.html' %}

{% block body %}
  <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 }}
  <!-- {{ 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)