Flask - 如何获取导致表单的页面的URL?

时间:2018-05-26 16:13:29

标签: python html flask

如果两个不同的网址导致相同的表单,您如何通过URL确定表单?

在网址"/page1""/page2"上,有一个"添加"导致使用相同网址"/form1"

的相同表单的按钮

如果"/page1"指向了表单页面,那么我希望在提交表单后重定向到"/page1",同样适用于"/page2"

这是我尝试过的代码:

@app.route("/page1", methods = ['GET', 'POST'])
def page1():

    # Do something

    return render_template("page1.html", title = "Page 1")


@app.route("/page2", methods = ['GET', 'POST'])
def page1():

    # Do something

    return render_template("page2.html", title = "Page 1")


@app.route("/form1", methods = ['GET', 'POST'])
def form1():

    form = SomeForm()
    # Do something

   if form.validate_on_submit():
       if request.url == "http://127.0.0.1:5000/page1":
           return(redirect(url_for('page1'))

       elif request.url == "http://127.0.0.1:5000/page2":
           return(redirect(url_for('page2'))    

    return render_template("form1.html", title = "Page 1", form = form)

但似乎我误解了request.url的作用,因为它返回了表单所在的网址。

那么,我应该使用什么方法来确定是否是导致表单的page1或page2?谢谢。

1 个答案:

答案 0 :(得分:1)

找到解决方案。您似乎需要使用request.referrer

@app.route("/form1", methods = ['GET', 'POST'])
def form1():

    form = SomeForm()
    # Do something

    # Use request.referrer before validation.
    prev_url = request.referrer

   if form.validate_on_submit():
       if request.url == "http://127.0.0.1:5000/page1":
           return(redirect(url_for('page1'))

   elif request.url == "http://127.0.0.1:5000/page2":
       return(redirect(url_for('page2'))    

return render_template("form1.html", title = "Page 1", form = form)