[英]Populate form (wtforms) in flask with data from database using psycopg2
I have a small form which I want to populate with the results of a query so that it can be edited afterwards. 我有一个小表单,我想填充查询的结果,以便以后可以编辑它。 I'm using Flask, WTForms and psycopg2 (no SQLAlchemy). 我正在使用Flask,WTForms和psycopg2(没有SQLAlchemy)。
View function : 查看功能:
@app.route('/editpositions/<row>', methods=['GET', 'POST'])
def editpositions_row(row):
conn = connect(host="localhost", user="postgres", dbname="portfoliotool", password="")
form = EditPositions()
if request.method == 'GET':
with conn.cursor() as cur:
sql = "SELECT isin, aantal FROM posities WHERE posnr = %(row)s"
cur.execute(sql, {"row": row})
data_pos = cur.fetchall()
form.isin.data = data_pos[0][0]
form.aantal.data = data_pos[0][1]
return render_template('editpositions.html', form=form)
The html template : html模板:
{% block app_content %}
<<div class="container">
<div class="row justify-content-center">
<div class="col">
<h1>Pas posities aan</h1>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.isin.label }}<br>
{{ form.isin(size=32) }}
</p>
<p>
{{ form.aantal.label }}<br>
{{ form.aantal(size=32) }}
<p>{{ form.submit() }}</p>
</form>
</div>
</div>
</div>
{% endblock %}
The page and form renders fine, but the two fields are not populated. 页面和表单呈现正常,但两个字段未填充。 I tested the sql query in the console and it returns the desired results, so I guess I'm missing something. 我在控制台中测试了sql查询,它返回了所需的结果,所以我想我错过了什么。 Can anybody help me? 有谁能够帮助我?
Eventually I found the problem. 最终我发现了这个问题。 The code mentioned here is correct. 这里提到的代码是正确的。 The problem was that "row" didn't receive the correct value due to an error elsewhere. 问题是由于其他地方的错误,“行”没有收到正确的值。
@app.route('/editpositions/<row>', methods=['GET', 'POST'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.