Skip to content Skip to sidebar Skip to footer

How To Create Dropdown Menu From Python List Using Flask And HTML

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 op

Solution 1:

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>

Solution 2:

you have a typo, replace colours to colour

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

replace to

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

Post a Comment for "How To Create Dropdown Menu From Python List Using Flask And HTML"