1

I want to select data from database table in MySQL. It is procedure in Python

@app.route('/formworkers.html')
def formworkers(): 
cursor = mysql.connection.cursor()
cur = cursor.execute("SELECT ID_worker, surname FROM workers")
return render_template('formworkers.html', workers0=cursor.fetchall())

And template in Jinja2

{% extends "layout.html" %}
    {% block body %}
    {% if session.logged_in %}
    <form action="" method=post class=add-worker >
      <dl>
        <dt>Surname:
        <dd><select name="worker0">
        {% for ID_pats, surname in workers0 %}
        <option value="{{ ID_worker }}">{{ surname }}</option>
        {% endfor %}
        </select>
        <br><br>
        <dd><input type=submit value="Submit">
      </dl>
    </form>
  {% endif %}
{% endblock %}

But the dropdown list does not contain data (for example [Ivanov, Petrov, Sidorov]) from the database, it contain values [surname, surname, surname]. Thank you.

5
  • could you add {{workers0}} in your template to check what is sent by the view ? Commented Nov 12, 2017 at 16:52
  • @PRMoureu, I write in template <option value="{{ workers0.ID_pats }}">{{ workers0.surname }}</option>, but dropdown list is empty, but have 3 empty elements Commented Nov 12, 2017 at 16:58
  • @PRMoureu, just write before for {{workers0}}? Commented Nov 12, 2017 at 17:09
  • just above the line <dd><select name="worker0">, only to see what it contains exactly Commented Nov 12, 2017 at 17:14
  • @PRMoureu, it output ({'ID_worker': 1L, 'surname': u'\u0418\u0432\u0430\u043d\u043e\u0432'}, {'ID_worker': 2L, 'surname': u'\u041f\u0435\u0442\u0440\u043e\u0432'}, {'ID_worker': 3L, 'surname': u'\u0421\u0438\u0434\u043e\u0440\u043e\u0432'}) Commented Nov 12, 2017 at 17:19

1 Answer 1

2

The query outputs a result as a list of dictionaries, so when you unpack it in the for loop, you get only a list of keys "ID_worker" and "surname" .

You can change the template like below to access the values :

{% for worker in workers0 %}

<option value="{{ worker.ID_worker }}">{{ worker.surname }}</option>

{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.