Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

html

flask

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> 
like image 997
DeeChok Avatar asked Aug 25 '17 08:08

DeeChok


People also ask

How do you create a drop-down list in Python?

Build A Paint Program With TKinter and Python In this case, we can use the Tkinter OptionMenu(win, menu_to_set, options) function. First, we will instantiate an object of StringVar(), then we will set the initial value of the dropdown menu.


2 Answers

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> 
like image 155
ettanany Avatar answered Sep 28 '22 03:09

ettanany


you have a typo, replace colours to colour

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

replace to

<option value= "{{colour}}" SELECTED>{{ colour }}</option>"                                      <!--  ^^^^ --> 
like image 31
Brown Bear Avatar answered Sep 28 '22 05:09

Brown Bear