37

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>

2 Answers 2

32

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>
Sign up to request clarification or add additional context in comments.

Comments

25

you have a typo, replace colours to colour

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

replace to

<option value= "{{colour}}" SELECTED>{{ colour }}</option>"
                                     <!--  ^^^^ -->

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.