【问题标题】:Populate form (wtforms) in flask with data from database using psycopg2使用 psycopg2 使用来自数据库的数据在烧瓶中填充表单(wtforms)
【发布时间】:2019-09-26 14:41:06
【问题描述】:

我有一个小表单,我想用查询结果填充它,以便之后可以对其进行编辑。我正在使用 Flask、WTForms 和 psycopg2(没有 SQLAlchemy)。

查看功能:

@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)

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 %}

页面和表单呈现正常,但两个字段未填充。我在控制台中测试了 sql 查询,它返回了所需的结果,所以我想我遗漏了一些东西。有人可以帮帮我吗?

【问题讨论】:

  • 如果填充表单是您的问题,最好包含表单声明代码..

标签: python postgresql flask psycopg2 flask-wtforms


【解决方案1】:

最终我发现了问题。这里提到的代码是正确的。问题是“行”由于其他地方的错误而没有收到正确的值。

@app.route('/editpositions/<row>', methods=['GET', 'POST'])

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 1970-01-01
    • 2020-05-08
    • 2015-03-03
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多