Issue
I am making a website with Flask and I am trying to create a dropdown menu filled with all regions in the regions table from my postgres database. Currently I have hardcoded the dropdown like this:
<label for="regions">Choose a region:</label>
<select name="regions" id="regions">
<option value="murray">Murray</option>
<option value="darling">Darling</option>
<option value="coast">Coast</option>
<option value="central">Central</option>
</select>
However, I would like to change this so that the dropdown is populated based off of an sql query of the table with all regions. Is this possible?
The SQL Query for the names of all the regions is:
select region_name from regions
Solution
In the backend (flask) you can fetch all the values from the Postgres database using the query:
# code to connect to db
...
# code to fetch from database
list_of_regions = db.execute("select region_name from regions")
Then pass on those values to the front end page:
@app.route("/")
def index():
return render_template("index.html", list_of_regions = list_of_regions)
On the front end you can loop through the values with Jinja and add the items to the dropdown:
<label for="regions">Choose a region:</label>
<select name="regions" id="regions">
{% for region in list_of_regions %}
<option value={{region.lower()}}>{{region}}</option>
{% endfor %}
</select>
Just replace your case-specific code with the general code that is provided above and it should be good to go. I was not sure about how to connect to postgres database as I have worked mostly with MySQL, so I guess this package might help you out better for that.
Answered By - Arpit Omprakash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.