I'm currently on CS50 PSET 9 Finance and stuck on the index.html portion of the assignment.

This is my code from assignment.py:

def index():

    stocks = db.execute("SELECT * FROM stockbuy WHERE id = ?", session.get("user_id"))

    cash = db.execute("SELECT * FROM users WHERE id = ?", session.get("user_id"))
    cash_remain =  float(cash[0]["cash"])
    for stock in stocks:
        tmp_cash = (float(stock["price"]) * float(stock["quantity"]))
        cash_remain = cash_remain - tmp_cash

    cash_remain = round(cash_remain, 2)
    return render_template("index.html", currentcash=cash_remain, stocks=stocks)


{% extends "layout.html" %}

{% block title %}
{% endblock %}

{% block main %}
     <table class="table table-striped">
                <td colspan="4"></td>
                <td>{{ totalvalue }}</td>
            {% for stock in stocks %}
                    <td>{{ stock["symbol"] }}</td>
                    <td>{{ stock["name"] }}</td>
                    <td>{{ stock["quantity"] }}</td>
                    <td>{{ stock["price"] }}</td>
                    <td>{{ stock["price"] * stock["quantity"] }}</td>
            {% endfor %}
                <td colspan="4">CASH</td>
                <td>{{ currentcash }}</td>
{% endblock %}

I have yet to implement {{ totalvalue }} as well.

Below is my Finance page:

Finance page

Below is my database for stocks: Database, showing multiple purchases

The issue I'm facing is that although i have multiple shares bought, i am unable to get the {%for%} loop in index.html to run over all the shares. I have tried to troubleshoot by passing different variables through the render_template, but I'm unsure of how to manipulate the data from db.execute through render_template and into html.

Any advice on which areas i should focus on would be much appreciated.

1 Answer 1


The {% for %} loop in index.html is running over all the shares (as selected by the query). The WHERE clause in the stockbuy query (WHERE id = ?) can never select both rows from that dataset because their id columns have different values.

  • Thanks for your reply :) Do you mean this section WHERE id = ?", session.get("user_id")? I mark all the shares with a seperate person_id (user_id) to check who they belong to.
    – Ryan Chua
    Commented Jun 9, 2021 at 13:45
  • yes, that WHERE clause is a problem. Answer has been edited for (hopefully!) clarity. Commented Jun 9, 2021 at 18:15
  • I understand now! Thanks a lot
    – Ryan Chua
    Commented Jun 10, 2021 at 3:27

You must log in to answer this question.

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