【问题标题】:Redirect() is not working when request.method == 'POST' in Flask [duplicate]当 Flask 中的 request.method == 'POST' 时,Redirect() 不起作用 [重复]
【发布时间】:2019-03-26 20:41:58
【问题描述】:

我正在构建一个 Web 应用程序并尝试使用 redirect() 函数链接两个 html。但是,当我单击“提交”按钮时,login.html 不会重定向到 success.html(即浏览器仍在 login.html 中)

下面是我的python代码:

from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('login.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      if request.form['username'] == 'admin':
         return redirect(url_for('success'))
      else:
         abort(401)
   else:
      return redirect(url_for('index'))

@app.route('/success', methods = ['POST', 'GET'])
def success():
   return 'logged in successfully'

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

还有html代码:

<html>
   <body>
      <form action = "login" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "username" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

【问题讨论】:

  • 发布 POST 而不是重定向时会发生什么?

标签: python flask


【解决方案1】:

您的字段名称在 html 和视图函数中不匹配。将name = "nm" 更改为name = "username"

<html>
   <body>
      <form action = "login" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "username" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多