0

How do I use the usd function with jinja?

I tried the following:

{% for row in rows %}
        <tr>
            <td>{{ row.Symbol }}</td>
            <td>{{ row.Name }}</td>
            <td>{{ row.Shares }}</td>
            <td>{{ row.Price | usd }}</td>
            <td>{{ row.Total | usd }}</td>
        </tr>
    {% endfor %}

But I get this error:

ValueError: Unknown format code 'f' for object of type 'str'

And this is the index function in application.py:

@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""

rows = db.execute("SELECT * FROM Portfolio WHERE id = :id", id=session["user_id"])
for x in range(len(rows)):
    if (rows[x]["Name"]) != '':
        symbol = rows[x]["Symbol"]
        quote1 = lookup(symbol)
        total1 = quote1["price"] * rows[x]["Shares"]
        db.execute("UPDATE Portfolio SET Price = :current_price WHERE Symbol = :Symbol AND Id = :Id",
                   current_price=float(quote1["price"]), Symbol=rows[x]["Symbol"], Id=session["user_id"])
        db.execute("UPDATE Portfolio SET Total = :current_total WHERE Symbol = :Symbol AND Id = :Id",
                   current_total=float(total1), Symbol=rows[x]["Symbol"], Id=session["user_id"])

# For [index][key]... : https://cs50.stackexchange.com/questions/23446/pset-7-buy-help
# Explaining [index][key]...: https://www.reddit.com/r/cs50/comments/bkquon/this_takes_place_in_the_login_function_in_finance/
# More explanation: https://www.reddit.com/r/cs50/comments/a1vwbm/confusion_in_finance_pset_index_function/
# for id... : (https://cs50.stackexchange.com/questions/23446/pset-7-buy-help)
cash1 = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])
portfolio_total = db.execute("SELECT SUM(Total) FROM Portfolio WHERE Id = :Id AND Symbol != '""'", Id=session["user_id"])
# To get # of rows (http://www.sqlitetutorial.net/sqlite-count-function/)
rows_num = db.execute("SELECT count(*) FROM Portfolio WHERE Id = :Id", Id=session["user_id"])
if rows_num[0]["count(*)"] > 2:
    print("rowsnum > 2...")
    grand_total = portfolio_total[0]["SUM(Total)"]
else:
    print("rowsnum < 2...")
    grand_total = cash1[0]["cash"]
# http://www.sqlitetutorial.net/sqlite-update/
# http://www.sqlitetutorial.net/sqlite-where/
db.execute("UPDATE Portfolio SET Total = :cash1 WHERE Symbol = 'CASH' AND Id = :Id",
           cash1=float(cash1[0]["cash"]), Id=session["user_id"])
db.execute("UPDATE Portfolio SET Total = :grand_total WHERE Symbol = '""' AND Id = :Id",
           grand_total=float(grand_total), Id=session["user_id"])

rows = db.execute("SELECT * FROM Portfolio WHERE id = :id", id=session["user_id"])
return render_template("index.html", rows=rows)

Why are "row.Price" and "row.Total" strings and not floats?

What am I doing wrong?

Thank you!

2
  • Please add at least your table's schema (for example the CREATE TABLE 'Portfolio'... SQL expression used, stating the types and modifiers of the columns).
    – Blauelf
    Commented Sep 3, 2019 at 17:18
  • imgur.com/a/38iJPDv
    – user23362
    Commented Sep 3, 2019 at 17:38

1 Answer 1

0

I created your table, I ran your code and it all worked fine.

Is it possible you have something corrupt in your Portfolio table from earlier testing?

If you clear out your table and do a new purchase, do you still get the same error?


(in response to comment)

The issue is that you have multiple rows for the same id, so when you send rows = rows to your jinja template, some of those rows don't have any values. Here's what I see when I register a new account and then buy 1 share of aapl.

[
{'Id': 79, 'Symbol': '', 'Name': '', 'Shares': '', 'Price': '', 'Total': 10000.0}, 
{'Id': 79, 'Symbol': 'AAPL', 'Name': 'Apple, Inc.', 'Shares': 1, 'Price': 205.7, 'Total': 205.7}, 
{'Id': 79, 'Symbol': 'CASH', 'Name': '', 'Shares': '', 'Price': '', 'Total': 9794.3}
]

Your jinja template will then treat each of these as a row, and as you can see row.Price is empty in the first and third rows. Since it's empty, the usd function can't format it, and you get the error.

Not sure why you have 3 rows for one id in your Portfolio table, but if you do, you'll need to make sure that you don't try to format any empty fields.

2

You must log in to answer this question.