python - 使用烧瓶将表单数据和列表值传递到 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() 中传递多个变量呢?
解决方案
你不能有这个:
@app.route('/')
def my_form():
return render_template('a.html')
@app.route('/', methods=['GET', 'POST'])
def my_form_post():
您已经定义了两个具有相同标识符的路由'/'
。后一个将被使用,第一个将被完全忽略。
当代码第一次执行(作为 GET)时,没有提供username
字符串的表单,因此不会呈现,这解释了您的输出,“欢迎参加测验谁是印度总统?”
推荐阅读
- python - 如何使用 CCDT 文件、用户 ID 和密码在 Python 中连接到 IBM MQ
- c# - 为什么这个从 C# 代码中提取的 Git 不起作用
- javascript - jQuery AJAX 调用获取 HTML 响应
- python - Raspberry Pi 自动播放来自 Spotify 的音乐
- python-3.x - 试图获取加入 Discord.py 的频道用户的频道 ID
- javascript - TypeError:无法读取未定义的属性“id”(用户未定义)
- sftp - 使用 python 上传 SFTP 文件
- ubuntu - Composer 在根文件夹中安装新项目
- python - 使用 random 如何生成没有小数的伪随机数?
- jpa - JPA更新父插入子