简体   繁体   中英

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

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 :

{% 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. 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM