python - 从 request.form.get() 获取 None
问题描述
我需要从 2 种不同的表格中获取数据。第一个“index.html”渲染采用用户选择的选项并将其存储在变量“item”中。
在“page2.html”上,“item”值在这里显示得很好。再一次,用户在文本框输入中输入了一些新数据,然后它被重定向到下一个渲染,“page3.html”
在“page3.html”上,它应该显示“index.html”和“page2.html”表单中的两个数据,但是当我尝试显示“item”值时,我得到“None”。为什么?
我尝试在单独的 app.route() 路由上执行此操作,但我也得到了 None 类型值。
app.py 文件:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if request.form.get('send') == 'send':
item = str(request.form.get('test1'))
return render_template('page2.html', item=item)
if request.form.get('send2') == 'send2':
item = str(request.form.get('test1'))
text = request.form.get('textbox')
return render_template('page3.html', item=item, text=text)
else:
return render_template('index.html')
app.run(debug=True)
index.html 文件:
<div align="center">
<form method="POST" action="{{ url_for('index') }}">
<select name="test1">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
</select>
<button type="submit" name="send" value="send">Send</button>
</form>
</div>
page2.html 文件:
<div align="center">
<form method="POST" action="{{ url_for('index') }}">
<h2>Previous selection: {{ item }}</h2><br>
<input type="text" name="textbox" value="Enter text">
<button type="submit" name="send2" value="send2">Send</button>
</form>
</div>
和 page3.html 文件:
<div align="center">
<h2>Your result is:</h2><br>
<h2>"{{ text }}" and "{{ item }}" </h2>
</div>
解决方案
将 item 的值存储在会话中,以便您以后可以访问它。完成后,您可以清除会话,例如session.pop("session_name", None)
if request.form.get('send') == 'send':
item = str(request.form.get('test1'))
session["test1"]=item
return render_template('page2.html', item=item)
if request.form.get('send2') == 'send2':
item = session.get("test1")
text = request.form.get('textbox')
return render_template('page3.html', item=item, text=text)
推荐阅读
- javascript - Reactjs _ Web 动画 APi - 尚不支持与基础值之间的动画
- python - Python why is 10e26 != 10**26 ? (Floating point inaccuracy?)
- php - 在容器中运行 cron
- python - 通过控制台参数从 python 脚本注入值
- c++ - 将灵活数组包装在匿名结构中时,MSVC 结构布局会发生变化吗?
- c++ - 在 CUDA9.2 及更高版本中使用模板默认参数未解决的外部函数错误
- r - 循环数据框中的列以使用 ggplot2 生成图
- python - Python 3:cProfile 结果的解释
- c# - 结果中添加了奇怪的小数
- html - 文本通过 div 的底部边框?