【问题标题】:Passing form data as well as list value into HTML Page using flask使用烧瓶将表单数据和列表值传递到 HTML 页面
【发布时间】:2018-08-01 19:22:23
【问题描述】:

我想在烧瓶中传递表单数据和列表值。但是表单数据不会出现在输出中。我是 python 新手。对不起,如果我的问题听起来太愚蠢了! 这是烧瓶代码

from flask import Flask
from flask import render_template,request
app = Flask(__name__)
@app.route('/')
def my_form():
    return render_template('a.html')

@app.route('/', methods=['GET', 'POST'])
def my_form_post():
result = request.form['username']
list1=['Who is the president of India?','Who is the captain of Team 
        India?','In which year was Mahatma Gandhi born?'];
return render_template('welcome.html', result=result, lis=list1)

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

这里是html代码:

<html>
<head>
<title>Welcome!</title>
</head>
<body>
Welcome to the quiz {{result.username}}
{{lis[0]}} 
</body>
</html>

这是表单页面:

<html>
<head>
<title>Welcome!</title>
</head>
<body>
<form method="POST" action="/">
Welcome to the quiz. Please Enter your name to proceed!
Name: <input type="text" name="username">
<input type="submit" name="submitdata">
</form>
</body>
</html>

我得到的输出是:
欢迎参加测验谁是印度总统?
为什么输入的名称没有出现在输出中?但是,如果我只是更改此行代码

return render_template('welcome.html', result=result)

我得到的输出是 Welcome to the quiz xyz。 那么为什么我不能在 render_template() 中传递多个变量呢?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    你不能拥有这个:

    @app.route('/')
    def my_form():
        return render_template('a.html')
    
    @app.route('/', methods=['GET', 'POST'])
    def my_form_post():
    

    您已经定义了两个具有相同标识符'/' 的路由。后一个将被使用,第一个将被完全忽略。

    当代码第一次执行(作为 GET)时,没有提供username 字符串的表单,因此它不会被渲染,这解释了您的输出,“欢迎参加测验谁是印度总统?”

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      相关资源
      最近更新 更多