我从Flask开始就遇到了这个问题。我需要重定向到url。当我尝试使用此代码时,请运行良好:
@app.route('/fa')
def hello():
return redirect(url_for('foo'))
@app.route('/foo')
def foo():
return 'Hello Foo!'
但是现在,我需要这个,但有一个渲染模板。这是代码,但后来我,但用户,烧瓶重定向并给出此错误:方法不允许
from flask import Flask, render_template, redirect, url_for
from forms import MyForm
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route("/signin", methods=("GET", "POST"))
def signin():
form = MyForm()
if request.method == 'POST':
if form.validate() == True:
return redirect(url_for('foo'))
elif request.method == 'GET':
return render_template("signin.html", form=form)
if __name__ == "__main__":
app.debug = True
app.run()
signin.html
{% block content %}
<h2>Sign In</h2>
<form method="POST" action="{{ url_for('signin') }}">
{{ form.hidden_tag() }}
{{ form.username.label }}
{{ form.username(size=20) }}
{{ form.password.label }}
{{ form.password(size=20) }}
{{ form.submit }}
</form>
{% endblock %}
MyForm.py
from flask_wtf import Form, TextField, PasswordField, DataRequired, SubmitField
class MyForm(Form):
username = TextField("Username", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
submit = SubmitField("Sign In")
def validate(self):
user = "franco"
if user == self.username:
return True
else:
return False
错误:
ValueError
ValueError: View function did not return a response
为什么?感谢
答案 0 :(得分:2)
问题不在于重定向(它工作正常),但在http方法是POST且表单无效的情况下。在这种情况下,signin
函数没有有效的响应,因此错误。
@app.route("/signin", methods=("GET", "POST"))
def signin():
form = MyForm()
if request.method == 'POST':
if form.validate() == True:
return redirect(url_for('foo'))
else:
# If method is POST and form failed to validate
# Do something (flash message?)
return render_template("signin.html", form=form)
elif request.method == 'GET':
return render_template("signin.html", form=form)