首页 > 解决方案 > 使用烧瓶将表单数据和列表值传递到 HTML 页面

问题描述

我想在烧瓶中传递表单数据和列表值。但是表单数据不会出现在输出中。我是 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() 中传递多个变量呢?

标签: pythonflask

解决方案


你不能有这个:

@app.route('/')
def my_form():
    return render_template('a.html')

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

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

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


推荐阅读