当我运行我的 flask 代码时,我目前遇到以下错误:
flask.debughelpers.FormDataRoutingRedirect - FormDataRoutingRedirect: A request was sent to this URL (http://localhost:5000/login) but a redirect was issued automatically by the routing system to "http://localhost:5000/login/". The URL was defined with a trailing slash so Flask will automatically redirect to the URL with the trailing slash if it was accessed without one. Make sure to directly send your POST-request to this URL since we can't make browsers or HTTP clients redirect with form data reliably or without user interaction.
我认为这与消息闪烁的位置有关,但我似乎无法弄清楚如何解决这个问题。我是 Flask 的新手,所以不完全确定解决这个问题的最佳选择是什么。
我包含了 index.py 和 login.html 文件以帮助重现此错误。先谢谢您的帮助! :)
app.py 的登录部分
@app.route('/login/', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
flash("Invalid username or password")
return redirect(url_for('dashboard'))
return render_template('login.html', form=form, errors=form.errors.items())
Login.html 模板
{% block body_content %}
<div class="container">
<form method="POST" action="/login">
{{ form.csrf_token }}
<div class="form-group">
{{ form.username }}
</div>
<div class="form-group">
{{ form.password }}
</div>
<div class="form-group">
{{ form.remember }}
</div>
<button type="submit" class="btn btn-primary">Sign In</button>
</form>
<div class="errors">
{% for field, err in errors %}
<p>{{field}} : {{err|join(', ')}}</p>
{% endfor %}
</div>
<div class="message-flash">
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
</div>
</div>
{% endblock %}
请您参考如下方法:
按照消息中的建议,在表单内的 action 属性中添加尾部斜杠:
<form method="POST" action="/login/">
最好使用 url_for 来构建 URL:
<form method="POST" action="{{ url_for('login') }}">
由于您使用处理帖子的相同 View 呈现表单,因此您可以省略 action。
<form method="POST">
