0

I am trying to program a simple dropdown where I do get data from the MySQLdb connection and cycle woth Flask through the resuls, but the data is not shown correctly. I have consulted and followed other posts yet in my case it does not work (no matter what I do).

Intended result:

    <option value="1">Appels</option>
    <option value="2">Bananas/option>
    <option value="3">Cherries</option>
    <option value="4">Peaches</option>

Actual result:

    <option value=""> (1, &#39;Appels&#39;) </option>
    <option value=""> (2, &#39;Bananas&#39;) </option>
    <option value=""> (3, &#39;Cherries&#39;) </option>
    <option value=""> (4, &#39;Peaches&#39;) </option>

I got the data in Flask from a MySQL database with MySQLdb with the following code:

    @app.route('/testbed', methods = ['POST', 'GET'])
    def testbed():
        cursor = mysql.connection.cursor()
        fruit = cursor.execute("SELECT id, type FROM fruit")
        return render_template('testbed.html', fruit=cursor.fetchall())

The corresponding HTML code:

    <select name="fldFruitPicker" class="form-select form-select-sm">
    {% for type in fruit %}
    <option value="{{ id }}"> {{ type }} </option>
    {% endfor %}
    </select>
0

1 Answer 1

0

You can change your html to smth like this:

 <select name="fldFruitPicker" class="form-select form-select-sm">
 {% for type in fruit %}
 <option value="{{ type[0] }}"> {{ type[1] }} </option>
 {% endfor %}
 </select>
  • Please, don't use type as variable name, it's reserved python word
  • You can use mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor initialization for dict as result. Then you can write not type[0], but type.id in your template. It will be more clear, I think.
Sign up to request clarification or add additional context in comments.

2 Comments

Hi zt50tz, First of all many thanks for the feedback! Coming back to the two points: 1) the word "type" was changed to "fruit_type", thank you for the suggestion 2) The part 'mysql.connection.cursor(MySQLdb.cursors.DictCursor)' was included in the app.py but now it runs in the following error: NameError: name 'MySQLdb' is not defined
Please, type import MySQLdb at the top of file that has this route and has cursor creation.

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.