我正在尝试编写一个简单的下拉列表,在其中我从 MySQLdb 连接获取数据并在 Flask 中循环遍历结果,但数据未正确显示。我已经咨询并关注了其他帖子,但就我而言,它不起作用(无论我做什么)。
预期结果:
<option value="1">Appels</option>
<option value="2">Bananas/option>
<option value="3">Cherries</option>
<option value="4">Peaches</option>
实际结果:
<option value=""> (1, 'Appels') </option>
<option value=""> (2, 'Bananas') </option>
<option value=""> (3, 'Cherries') </option>
<option value=""> (4, 'Peaches') </option>
我使用 MySQLdb 从 MySQL 数据库获取 Flask 中的数据,代码如下:
@app.route('/testbed', methods = ['POST', 'GET'])
def testbed():
cursor = mysql.connection.cursor()
fruit = cursor.execute("SELECT id, type FROM fruit")
return render_template('testbed.html', fruit=cursor.fetchall())
对应的HTML代码:
<select name="fldFruitPicker" class="form-select form-select-sm">
{% for type in fruit %}
<option value="{{ id }}"> {{ type }} </option>
{% endfor %}
</select>
你可以将你的 html 更改为这样:
<select name="fldFruitPicker" class="form-select form-select-sm">
{% for type in fruit %}
<option value="{{ type[0] }}"> {{ type[1] }} </option>
{% endfor %}
</select>
type
作为变量名,它是Python的保留字mysql.connection.cursor(MySQLdb.cursors.DictCursor)
光标初始化作为结果。然后您可以在模板中不写 type[0]
,而是写 type.id
。我想这样会更清楚。