Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing value from a drop down menu to a Flask template

I am having an issue passing an item selected from an HTML drop down menu to a SQL query.

I'm not exactly sure what concept is missing from my code to make this work. Most examples I have found are in PHP and I'm not sure how to translate it to Python.

Here is the scenario. I'm using Flask and Sqlite and am try to let the user select an item from an HTML drop down menu. The item selected from the drop down menu will be used in a SQL query to retrieve information from a database and then display those results on a new page.

An example, the user selects "Red" from a drop down that has 3 options (Red, Blue, Green) and clicks a submit button. "Red" will be passed to a SQL query in my app.py file that will retrieve all data from rows where color = "Red". That retrieved data will then be displayed on /results.html.

I believe my problem is that I'm not correctly attributing a value to the items in my drop down menu and then passing that value to my Python code that is running the SQL query. This is my assumption on how this should work, but I might be missing something bigger here.

I have tried lots of bits of HTML to make this work, but I'm not even sure that is where my problem is occurring. When I hit "Submit" I'm taking the new page, but nothing from the database is displayed

Here is my code, for my 2 views ('/' & 'results.html') and my Python code:

@app.route('/results.html', methods=['GET','POST'])
def results():
    g.db = connect_db()

    cur = g.db.execute("SELECT * FROM all_items WHERE name = '{}'".format('Red'))
    posts = [dict(item=row[0], name=row[1]) for row in cur.fetchall()]
    g.db.close()
    return render_template('results.html', posts=posts)

Here is View where the the drop down menus exist

<select name="Item_1">
    <option value="Red">Red</option>
    <option value="Green">Green</option>        
</select>

<form name="Item_1" action="results.html" method='POST'>
    <button type="submit">Compare!</button>
</form>

Here is the View where the results from selecting "Red" should be displayed

% extends "template.html" %}
{% block content %}
<h2>Results</h2>

{% for p in posts %}
    <strong>Item:</strong> {{ p.item }}
    <strong>Name:</strong> {{ p.name}}  
{% endfor %}
{% endblock %}
like image 453
Alex Avatar asked May 09 '14 05:05

Alex


1 Answers

You need to put your select inside the form.

<form name="Item_1" action="results.html" method='POST'>
    <select name="Item_1">
        <option value="Red">Red</option>
        <option value="Green">Green</option>        
    </select>
    <button type="submit">Compare!</button>
</form>

An even better way to declare the form would be

<form name="Item_1" action="{{ url_for('results') }}" method="POST">
like image 65
dirn Avatar answered Oct 03 '22 01:10

dirn