[英]CS50 Finance - index not displaying Portfolio correctly
我無法讓代碼正確顯示 index.html 中的投資組合。
我對這個 function 的邏輯是獲取一個用戶擁有的所有股票和現金的列表,然后在“for”循環中,查找每只股票的公司名稱和當前價格,總值,然后插入所有將該信息放入一個新的字典列表 (display_portfolio)。 然后render_template 應該顯示“display_portfolio”和這個信息,以及用戶的總現金和所有東西的總價值。 但是,在我當前的設置中,它顯示的是總現金和總計,但沒有顯示個股。 我真的不知道為什么會這樣,我不確定問題是在我的 html 還是在 flask function 本身。
這是 function:
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
# Retrive portfolio
portfolio = db.execute("SELECT symbol, SUM(amount) as amount FROM purchases WHERE id = ? ORDER BY symbol", (session["user_id"]))
user_cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
cash = user_cash[0]["cash"]
display_portfolio = []
shares_total = 0
# loop through portfolio symbols to access name and share price for each symbol
for row in portfolio:
requested_quote = lookup(row["symbol"])
symbol = row["symbol"]
amount = row["amount"] #shares
price = float(requested_quote["price"])
name = requested_quote["name"]
share_total = (float(amount) * price)
shares_total = shares_total + share_total
display_portfolio.append({'symbol':symbol, 'name':name, 'shares':amount, 'price':price, 'share_total':share_total})
grand_total = shares_total + cash
return render_template("index.html", display_portfolio = display_portfolio, cash = cash, grand_total = grand_total)
這是索引。html:
{% extends "layout.html" %}
{% block title %}
Portfolio
{% endblock %}
{% block main %}
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Shares</th>
<th>Price</th>
<th>TOTAL</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3"></td>
<td>TOTAL</td>
<td>{{ grand_total | usd }}</td>
</tr>
</tfoot>
<tbody>
{% for row in display_portfolio %}
<tr>
<td>{{ display_portfolio.symbol }}</td>
<td>{{ display_portfolio.name }}</td>
<td>{{ display_portfolio.shares }}</td>
<td>{{ display_portfolio.price }}</td>
<td>{{ display_portfolio.total }}</td>
</tr>
{% endfor %}
<td colspan="3"></td>
<td>Cash</td>
<td>{{ cash | usd }}</td>
</tbody>
</table>
</div>
{% endblock %}
我還應該注意,當我將“| usd”添加到“display_portfolio.price”時,它會顯示:
<td>{{ display_portfolio.price | usd }}</td>
我也得到了一個完全獨立的錯誤,不知道為什么它可以用現金而不是這個。
我可以確認 sql 數據庫中存在“投資組合”變量正在檢索的購買。
這是它的樣子:
任何幫助將不勝感激,謝謝!
允許的父母:一個
<table>
元素。<tfoot>
必須出現在任何<caption>
、<colgroup>
、<thead>
、<tbody>
或<tr>
元素之后。 請注意,這是 HTML5 的要求。
懷疑 Cash line 已顯示,因為它缺少<tr>
標記。
來自 W3C 的Nu HTML 驗證器是你的朋友:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.