I am trying to work on pset7, but am having a problem printing it out to the screen in the table format. I have all the values I need (the values I have are correct), but just can't figure out how to display these last 2 attributes on the html table. (I'm not worried about Your Current Cash Balance and Grand Total, that should be easy after this).

I just basically (in sql / db.execute) grouped by symbol and then looked up the price for each symbol (thanks to lookup function) and stored each symbol's current price in the currentprices list so I can iterate through it in HTML / Jinja. Thanks for any guidance

Python (using flask micro-framework):

def index():

    stocks = db.execute("SELECT stock, symbol, Sum(quantity) AS quantities FROM portfolio WHERE user_id_fk = :user_id_fk GROUP BY stock, symbol ORDER BY stock",
    user_id_fk = session["user_id"])

    currentprices = []

    # get current price for each group (ie AAPL) with help from lookup function (which remember, returns a dict)
    for stock in stocks:
        symbol = str(stock["symbol"])
        quote = lookup(symbol)

    cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])

    # render the template with the stored result sets from queries
    return render_template("index.html", stocks = stocks, cash = cash, currentprices = currentprices)

Here's the index.html / Jinja2 code:

{% extends "layout.html" %}

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

{% block main %}

            <th>Current Value</th>
            <th>Total Value</th>

        {% for stock in stocks %}
                <td>{{ stock["stock"] }}</td>
                <td>{{ stock["quantities"] }}</td>
        {% endfor %}

        {% for currentprice in currentprices %}
                <td>current value is {{ currentprice }}</td>
                <td>total value (shares * price) here</td>
        {% endfor %}




1 Answer 1


Since "stocks" are in one list and "currentprices" are in another list you will get this result when you use two lists and two loops.

  • One solution would be to use one loop and use currentprices[i] where i is indexed to the row in the "stocks" list.
  • Another option would be to add a "price" key to each "stocks" row in the index() function instead of building a separate "currentprices" list.
  • Thanks! Your first solution worked for me. Ftlom I couldn't figure that out, this is my first foray with Jinja syntax or any templating language. Thanks!
    – Chris Koro
    Feb 11, 2017 at 20:34
  • I'm currently struggling with this. How do you do that first solution: index i to the row in stocks list?
    – Scott
    Mar 19, 2017 at 17:31
  • jinja2 loop.index can help with solution 1
    – daniel ho
    May 18, 2017 at 5:47

You must log in to answer this question.

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