I am implementing a dropdown menu on a web page. In my controller code I'm grabbing data from a sqlite database and storing it in a variable called "portfolio". I'm then iterating over it on my html page with Jinja. I followed this same process with success on another page. The only difference is that that info was displayed in a table rather than a dropdown menu. I suspect something about storing items in the "option value" tags is causing me a problem.
Anyone able to help point in the right direction? Thanks.
My problem: no stocks displaying in dropdown menu
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
# If a form is submitted
if request.method == "POST":
symbol = request.form.get("symbol")
shares_to_sell = int(request.form.get("shares"))
# Access user's stock info
portfolio = db.execute("SELECT symbol, SUM(shares) AS shares FROM purchases WHERE users_id = ? GROUP BY symbol", session["user_id"])
for stock in portfolio:
folio_symbol = stock["symbol"]
shares_owned = int(stock["shares"])
# Ensure stock is selected
if not symbol:
return apology("Must select a stock to sell", 403)
# Ensure user owns that stock
if symbol != folio_symbol:
return apology("Can only sell stocks you own", 403)
# If no shares selected
if shares_to_sell < 1:
return apology("Must select a number of shares to sell", 403)
# If user does not own enough shares
if shares_owned < shares_to_sell:
return apology("User does not own enough shares to sell", 403)
# Subtract shares sold from purchases table
db.execute("UPDATE purchases SET shares = ? WHERE users_id = ?", shares_owned-shares_to_sell, session["user_id"])
# Adjust cash in users table
users = db.execute("SELECT * FROM users WHERE id = ?", session["user_id"])
cash = users[0]["cash"]
stock_info = lookup(symbol)
sell_amt = shares_to_sell*stock_info["price"]
db.execute("UPDATE users SET cash = ? WHERE id = ?", cash+sell_amt, session["user_id"])
flash("Sold!")
return redirect("/", portfolio=portfolio, stock=stock)
else:
return render_template("sell.html")
HTML page:
{% extends "layout.html" %}
{% block title %}
Sell Stocks
{% endblock %}
{% block main %}
<h2>Sell Stocks</h2>
<br>
<p>Offload your shares below.</p>
<br>
<form action="/sell" method="post">
<div class="form-group">
<select class="form-control" name="symbol">
<option disabled selected value>Stock</option>
{% for stock in portfolio %}
<option value="{{ stock.folio_symbol }}">{{ stock.folio_symbol }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<input class="form-control" name="shares" placeholder="Shares" type="text">
</div>
<button class="btn btn-primary" type="submit">Sell</button>
</form>
{% endblock %}
SOLVED: I forgot to grab my database info under my GET condition. Thus, the dropdown wasn't populating because there was no data available under that condition to populate it.