It is very necessary for web applications to fill a dropdown or a combo box with data stored in another table. You should learn this as it is important for the creation of web applications for maintaining consistency and data. For instance, users punching the city names but they may write incorrect spellings. So, it is better if you have a table that has all the cities with their codes stored and fill the data from this table. In this way, when a user will select a city name from the dropdown, it will fetch its ID and pass it on with the POST method. There is a very least chance of storing various spellings of the same city in this way. Additionally, the user will have the advantage of typing lesser now. In this blog, we will discuss the steps and code of filling a Flask dropdown menu.

Flask dropdown menu

Also Read: Python programming structure: Everything you need to know

Flask dropdown menu

The steps for the Flask dropdown menu are as follows:

1. Get the dataset from a Master Table

In order to fill a Flask dropdown menu and PostgreSQL web application, you have to use the or file. You have to add the code in the route procedure that will render the HTML file with a web form containing the dropdown. Now you have to execute a SELECT command on the database connection. Then find the list with tuples ( city_id,city_name) values.

2. Pass this dataset as a parameter

The route procedure returns render_template in the return statement. Here you have to pass the created list ( city_id,city_name) tuples as parameters. You can use it to fill the Combo box/ drop-down/ Option box.

3. Fill the dropdown using Jinja for loop

Lastly, you will fill a Dropdown/Combo in Flask and PostgreSQL with the help of Jinja for a loop. The SELECT HTML tag with the name of the SELECT dropdown will introduce the loop. It will be referred to when the POST method returns the form data. OPTION will be created by using the name as the display value and id as the value part in Jinja for a loop.

In the example code given below, we have used the table cities having two columns city_id and city_name.

Now we want to show the city name and when a user selects a certain city name, the city_id must be returned.

You have to add this route in

def input():
    cityList=db.execute("SELECT * FROM cities order by city_name")
    return render_template("input.html",cityList=cityList )

Now you have to add the following code in the  input.html stored in the templates folder. This is in order to create the combo box/ dropdown with the list of cities from the table cities.

Choose a City<SELECT name="city">
{% for c in cityList %}
	<OPTION value={{c.city_id}}>{{c.city_name}}</option>
{% endfor %}


We hope that you got to know everything about the Flask dropdown menu. Thank you for reading our blog!

Categorized in:

Tagged in: