当 Flask 中的 request.method == 'POST' 时,重定向()不起作用

我正在构建一个 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>


呼如林
浏览 358回答 1
1回答

ibeautiful

您的字段名称在 html 和视图函数中不匹配。更改name = "nm"为name = "username":<html>&nbsp; &nbsp;<body>&nbsp; &nbsp; &nbsp; <form action = "login" method = "post">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p>Enter Name:</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p><input type = "text" name = "username" /></p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p><input type = "submit" value = "submit" /></p>&nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp;</body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python