我正在尝试从复选框中获取值列表。
我发现了一篇旨在解决我的问题的帖子(How to get if checkbox is checked on flask),但是,我仍然收到此错误:错误请求浏览器(或代理)发送了此服务器无法理解的请求。< / p>
我将发布我的整个代码块以将其放在上下文中,但如果没有添加复选框,它可以正常工作。事实上,我有一个下拉菜单相同的选项,它工作正常。
请注意,虽然我定期在python中编码,但我是html和flask的初学者。
<form action='/user_rec' method='POST' id='submitform'>
<input type='text', placeholder='user id' name='user_input'>
<button type="submit" class="btn btn-success">Recommend</button>
<br><br>
<h2>Other Options</h2>
<h5>Best Number of Players</h5>
<div class="checkbox">
<label><input type="checkbox" name="check" value="1">1</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="2">2</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="3">3</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="4">4</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="check" value="5">5+</label>
</div>
<h5>Minimum Play Time (minutes)</h5>
<input type="text", placeholder='0' name='min_time'>
<br><br>
<h5>Maximum Play Time (minutes)</h5>
<input type="text", placeholder='500000' name='max_time'>
</form>
和我的python代码:
@app.route('/user_rec', methods=['POST'])
def button1():
user_name = (request.form['user_input'])
best_num_player = (request.form['best_num_player'])
min_time = (request.form['min_time'])
max_time = (request.form['max_time'])
players = request.form.getlist('check')
答案 0 :(得分:6)
我认为您的代码存在两个问题:
'best_num_player'
不是dict格式的密钥。以下是您可以尝试的示例app.py
。 (我假设你将模板命名为index.html
)
from flask import Flask, render_template, redirect, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user_rec', methods=['POST'])
def user_rec():
user_name = request.form.get('user_input')
min_time = request.form.get('min_time')
max_time = request.form.get('max_time')
players = request.form.getlist('check')
print(user_name, min_time, max_time, players)
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)