首页 > 解决方案 > 烧瓶重定向功能未重定向到正确的页面

问题描述

我有页面应用程序路线。这是我的 python 烧瓶代码。


from flask import Flask, render_template, flash, redirect
from forms import RegistrationForm, LoginForm

app = Flask(__name__)


@app.route("/")
@app.route("/home", methods=["GET", "POST"])
def home():
   return render_template("home.html")


@app.route("/dashboard", methods=["GET", "POST"])
def dashboard():
    return render_template("dashboard.html")


@app.route("/register", methods=["GET", "POST"])
def register():
    form = RegistrationForm()
    app.logger.debug(form.validate_on_submit())
    if form.validate_on_submit():
        return redirect("dashboard")

    return render_template("registerPage.html", title="Register", forms=form)

当我运行它时,它会重定向到http://localhost:5000,而它应该重定向到http://localhost:5000/dashboard
发生了什么?

标签: pythonhtmlredirectflaskhttps

解决方案


添加导入url_for

from flask import url_for

然后在重定向中使用它:

return redirect(url_for("dashboard"))

url_for函数采用函数的名称并构造该函数的“url”。

您在 DropBox 上发布了指向您的项目文件的链接。

在您的模板中registerPage.html,您需要更改:

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

至:

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

如果您/改为发布,该register函数将永远不会看到发布的数据,也永远不会将用户重定向到仪表板。


推荐阅读