I am able to make 1 purchase which appears on my index page, however if I try buy any further stocks my cash goes down but the stocks are not shown and aren't inserted into my portfolio.

Here is my python code for 'index':

rows = db.execute("SELECT * FROM portfolio WHERE id = :user_id", user_id = session["user_id"])
cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])[0]["cash"]
value = float(cash)

for i in range(len(rows)):
    symbol = rows[i]["symbol"]
    shares = rows[i]["shares"]
    price = rows[i]["price"]
    total = rows[i]["total"]
    value += total

return render_template("index.html", rows = rows, cash = usd(cash), value = usd(value))

This is the part of my 'buy' function which updates my portfolio:

    # calculate total price
    total = quote["price"]*amount
    cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])[0]["cash"]

    # check if user has sufficient cash and update portfolio
    if(cash >= total):
        db.execute("INSERT INTO portfolio (id, price, shares, symbol, 'when', total) VALUES (:id, :price, :shares, :symbol, date('now'), :total)", id = session["user_id"], price = quote["price"], shares = amount, symbol = quote["symbol"], total = total)
        db.execute("UPDATE users SET cash = cash - :price WHERE id = :id", price = total, id = session["user_id"])
        return apology("insufficient cash for chosen stock")

    # Redirect user to home page
    return redirect("/")

I doubt that my problem is to do with my index html code but here it is as well:

<table class = "table table-striped">
        {% for row in rows %}
            <td>{{ row.symbol }}</td>
            <td>{{ row.shares }}</td>
            <td>{{ row.price | usd }}</td>
            <td>{{ row.total | usd }}</td>
        {% endfor %}

            <td colspan="2"></td>
            <td>{{ cash }}</td>

                <td colspan="3"></td>
                <td>{{ value }}</td>


After reading through all my code a couple of times, I found that I had accidentally set the id field in my portfolio table as primary key so I couldn't repeat any purchases with the same id.

You must log in to answer this question.

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