关于python:Flask中request.method ==’POST’时python:Redirect()不起作用

Redirect() is not working when request.method == 'POST' in Flask

本问题已经有最佳答案,请猛点这里访问。

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

下面是我的python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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代码:

1
2
3
4
5
6
7
8
9
<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>


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

1
2
3
4
5
6
7
8
9
<html>
   <body>
      <form action ="login" method ="post">
         <p><center>[wp_ad_camp_2]</center></p><p>Enter Name:</p>
         <p><input type ="text" name ="username" /></p>
         <p><input type ="submit" value ="submit" /></p>
      </form>
   </body>
</html>