How to create dropdown menu from python list using Flask and HTML

Question:

I’m trying to create a dropdown menu in HTML using info from a python script. I’ve gotten it to work thus far, however, the html dropdown displays all 4 values in the lists as 4 options.

Current: Option 1: Red, Blue, Black Orange; Option 2: Red, Blue, Black, Orange etc. (Screenshot in link)
Current

Desired: Option 1: Red
Option 2: Blue
etc.

How do I make it so that the python list is separated?

dropdown.py

from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True


@app.route('/', methods=['GET'])
def dropdown():
    colours = ['Red', 'Blue', 'Black', 'Orange']
    return render_template('test.html', colours=colours)

if __name__ == "__main__":
    app.run()

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dropdown</title>
</head>
<body>
<select name= colours method="GET" action="/">
    {% for colour in colours %}
    <option value= "{{colour}}" SELECTED>{{colours}}</option>"
    {% endfor %}
</select>

</body>
</html>
Asked By: DeeChok

||

Answers:

you have a typo, replace colours to colour

<option value= "{{colour}}" SELECTED>{{colours}}</option>"

replace to

<option value= "{{colour}}" SELECTED>{{ colour }}</option>"
                                     <!--  ^^^^ -->
Answered By: Brown Bear

You need to use {{colour}} in both places (instead of {{colours}} in the second place):

<select name="colour" method="GET" action="/">
    {% for colour in colours %}
        <option value="{{colour}}" SELECTED>{{colour}}</option>"
    {% endfor %}
</select>

Note that using selected inside the loop will add selected attribute to all options and the last one will be selected, what you need to do is the following:

<select name="colour" method="GET" action="/">
  <option value="{{colours[0]}}" selected>{{colours[0]}}</option>
  {% for colour in colours[1:] %}
    <option value="{{colour}}">{{colour}}</option>
  {% endfor %}
</select>
Answered By: ettanany
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.