Python Flask-render_template不显示传递的值

时间:2019-02-21 17:20:46

标签: python flask

我是Python的新手,正在尝试开发简单的Web应用程序。

在下面的代码中,我试图从数据库中检索值并在HTML页面上进行整理 我能够看到HTML页面,但看不到传递的值。请在这里帮助我。 Python代码

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

     if request.method == 'POST':
print('in get method')
userid = request.form['userId']
print('user id ', userid)
conn = mysql.connect()
cursor = conn.cursor()

# Get User Details
print('execut sql')
result = cursor.execute("SELECT * FROM tbl_user WHERE user_id= %s", [userid])
if result > 0:
    data = cursor.fetchall()
    for row in data:
        userId = row[0]
        name = row[1]
        userName = row[2]
        password = row[3]
        return render_template("userDetails.html", userId=userId, name=name, userName=userName, password=password)
else:
    return render_template('index.html')

cursor.close()

下面的HTML代码。

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
  <head>
    <title>Python Flask Bucket List App</title>


    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body>

      <h3 class="text-muted">Python Flask App </h3>
      </div>
      <div class="jumbotron">
          <h1>Display User Details</h1>
        <div class="jumbotron">
            <form class=class="form-userDetails, action="/userDetails", method="POST">
                User ID:<input type="text" name="userId" class="form-control">
                Name <output name="name" id="name" for="userId" class="form-control"></output>
                User Name <output name="userName" id="userName" for="userId" class="form-control"></output>
                Password <output name="password" id="password" for="userId" class="form-control"></output>
                </br>
                <button id="btnretive" class="btn btn-lg btn-primary btn-block" type="submit">Retrive</button>

            </form>
     </div>

      <div class="Footer">
          <footer class="footer">
            <p>&copy; Company 2015</p>
          </footer>
      </div>

    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

@DRaj,您使用的<output>标签错误。根据规范,

  

HTML Output元素()是一个容器元素,网站或应用程序可以在其中注入计算结果或用户操作的结果。

有关更多信息和示例,请参考此Mozilla page


现在, Flask使用 Jinja2模板引擎进行HTML呈现。因此,输出值的正确方法是在HTML的表达式定界符 {{ ... }}内输入python变量,然后将变量传递给render_template方法。

<form class=class="form-userDetails, action="/userDetails", method="POST">
    User ID:<input type="text" name="userId" class="form-control">
    Name: {{ name }}
    User Name: {{ userName }}
    Password: {{ password }}
    </br>
    <button id="btnretive" class="btn btn-lg btn-primary btn-block" type="submit">Retrive</button>

</form>

并且python代码应该是:-

return render_template("userDetails.html", name=name, userName=userName, password=password)

有关更多信息,请参阅此Jinja template designer documentation