I am trying to do the index part of this pset but the problem is since I want the price to be the current price, not price bought, I need to use the lookup function. But how do I display the price? The problem with my code is that it doesn't display the price and the total per stock. Also, how will I present the price using the usd() function since I can't use usd in the html. Thank you in advance. My code is this:

def index():
"""Show portfolio of stocks"""
userid = session["user_id"]
index = db.execute("SELECT symbol, SUM(shares) AS shares, name FROM transactions WHERE user_id = :user_id GROUP BY symbol", user_id=userid)
# this will get the cash of the user
cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=userid)
money = cash[0]["cash"]
total = money
for row in index:
    quote = lookup(row["symbol"])
    shares = int(row["shares"])
    price = float(quote["price"])
    cost = price * shares
    total = total + cost

return render_template("index.html", index=index, money=usd(money), total=usd(total))

and my HTML code is

    {% for row in index %}
    {% endfor %}
        <td colspan = "3"></td>
        <td colspan = "4"></td>

enter image description here


If I remember correctly about jinja, it should be something like:

{% for row in index %}
        <td>{{row.name}}  </td>
        <td>{{row.price}} </td>
        <td>{{row.cost}}  </td>
 {% endfor %}
  • I tried changing it but I think the main problem is in the code. – jankendrick Apr 13 '20 at 21:49

I'm not sure if my solution was correct but I've calculated cost (aka shares*price) inside the html file: {{ row["shares"]*row["price"] }} and it worked! As for the displaying the price it might be quicker to change your db table to include price so then you can loop over as a row instead of using quote. Hope that helps :)


When you run your index query on the database, the result is a list of dictionaries. When you do

for row in index:

an output is generated, but you are not storing the outputs. So you need containers to store the output. Then you will now send the containers to your HTML and use jinja for loops to iterate over the items. HINT: I initialised an empty variable and an empty list before the for loop while I incremented those as the for loop ran.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .