簡體   English   中英

使用psycopg2使用數據庫中的數據填充燒瓶中的表單(wtforms)

[英]Populate form (wtforms) in flask with data from database using psycopg2

我有一個小表單,我想填充查詢的結果,以便以后可以編輯它。 我正在使用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查詢,它返回了所需的結果,所以我想我錯過了什么。 有誰能夠幫助我?

最終我發現了這個問題。 這里提到的代碼是正確的。 問題是由於其他地方的錯誤,“行”沒有收到正確的值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM