Flask returns 'Method not allowed' 提交表单时

Flask returns 'Method not allowed' when submitting form

我正在密切关注very brief tutorial from Flask-wtf here。我有一个问题,在我的 submit 页面表单中提交我的名字后,它给出了“405 Method Not Allowed”消息而不是指导我到成功页面。

from flask import Flask, render_template, redirect
from forms import MyForm

app = Flask(__name__)
app.secret_key = 'mysecretKey'


@app.route('/submit', methods=('GET', 'POST'))
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/success')
    return render_template('submit.html', form=form)


@app.route('/success')
def success():
    return "Well done for entering your name!"


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

我的表格在这里:

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired


class MyForm(FlaskForm):
    name = StringField('name', validators=[DataRequired()])

我的 submit.html 代码如下所示(就像在教程中一样):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Password page</title>
</head>
<body>

<form method="POST" action="/">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name(size=20) }}
    <input type="submit" value="Go">
</form>

</body>
</html>

编辑:if form.validate_on_submit() 条件不 return 真所以循环的内容不执行。我在其中添加了一个简单的打印语句,但没有执行。

问题是您没有提到方法 success 应该处理 POST 个请求。

from flask import Flask, render_template, redirect
from forms import MyForm

app = Flask(__name__)
app.secret_key = 'mysecretKey'


@app.route('/submit', methods=('GET', 'POST'))
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/success')
    return render_template('submit.html', form=form)


@app.route('/success')
def success():
    return "Well done for entering your name!"


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

from flask import Flask, render_template, redirect
from forms import MyForm

app = Flask(__name__)
app.secret_key = 'mysecretKey'


@app.route('/submit', methods=['GET', 'POST'])
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/success')
    return render_template('submit.html', form=form)

# This is the change I made.
@app.route('/success', methods=['POST'])
def success():
    return "Well done for entering your name!"


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

如果我假装确切地知道所有相对路径是如何解析的,那我就是在撒谎。但是,您可以通过更改来解决此问题:

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

至:

<form method="POST" action="{{ url_for('submit') }}">

这是将问题传递给图书馆解决确实有意义的事情之一。使用 url_for 渲染模板时,它也适用于 Jinja2。