Search code examples
cs50finance

INDEX only pulling one row of data from database


For the life of me I cannot get my index page to properly display the data from my database. I have tried multiple methods and research on several sites. I'm thinking it is something right in front of my face, but right now I can't see the forest through the trees. I have included my code below.

Application:

@app.route("/")
@login_required
def index():

    users = db.execute("SELECT * FROM users WHERE id = :user_id", user_id=session["user_id"])
    stocks = db.execute("SELECT * FROM transactions WHERE id = :user_id", user_id=session["user_id"])
    quotes = {}

    for symbol in stocks:
        quotes[symbol["symbol"]] = lookup(symbol["symbol"])

    return render_template ("index.html", quotes=quotes,stocks=stocks, symbol=symbol)

index.html:

{% extends "layout.html" %}

{% block title %}
    Portfolio
{% endblock %}

{% block main %}
    <table class="table table-striped">
        <tr>
            <th> Symbol</th>
            <th> Current Share Price</th>
            <th> Shares Owned</th>
            <th> Shares Owned Value</th>
        </tr>

        {% for stock in stocks %}
        <tr>
            <td>{{symbol.symbol}}</td>
             <td>{{quotes[stock.symbol]["price"] | usd }}</td>
            <td>{{symbol.shares}}</td>
            <td>{{symbol.total_price}}</td>
        </tr>
        {% endfor %}

    </table>
{% endblock %}

Finally here is a screenshot of my index.html as it generates now: index

And the data in my database table: enter image description here

As you can see, the table displays the symbol, shares and total price from only one of the transactions. It shows the correct updated price for each stock, but I can't get it to pull the correct data from the table. Thank you so much for any help.


Solution

  • symbol has the value of the last iteration of for symbol in stocks:. Looks like the html should be creating the td elements from stock ({% for stock in stocks %}) not from symbol.

    Suggestion to simplify:

    In the for symbol in stocks: loop in the .py, add a key to the symbol dictionary for price. That would render the quotes object unnecessary and the stocks list would be self contained.