Skip to main content
5 of 8
added 2 characters in body

CS50 finance: Sell function.(Dropdown list of user shares NOT displayed via sell.html)

Purpose of Sell: to make sure the shares bought can be sold by selecting it through a dropdown list displaying symbols of share bought. I am trying to replicate the cs50 finance default page.

enter image description here

I have 3 tables in my SQL database: - user (default), portfolio, history

Below is my sell function from application.py. I am using for-loop to make sure that bought shares in portfolio can be selected in sell.html (like in index.html)

# SELL
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
  if request.method == "POST":
      if not request.form.get("symbol"):
          return apology("Missing symbol")

    # ensure password was submitted
    elif not request.form.get("shares"):
        return apology("Missing shares")

    # Check how much cash and what stocks user have
    cash = db.execute("SELECT cash FROM users WHERE id=:id",
                   id=session["user_id"])
    stocks = db.execute("SELECT shares, symbol FROM portfolio WHERE id=:id",
                      id=session["user_id"])

    # update each symbol prices and total
    # for stock in stocks:
    symbol = request.form.get("symbol")
    stock = lookup(symbol)
    symbol = stock["symbol"]
    shares = int(stock["shares"])
    price = stock["price"]
    total = shares * price

    db.execute("UPDATE portfolio SET price=:price, total=:total WHERE id=:id AND symbol=:symbol",
            price=usd(stock["price"]), total=usd(total), id=session["user_id"], symbol=symbol)

    # Calculate how many shares of this stock user has
    share_qty = db.execute("SELECT shares FROM total WHERE symbol=:symbol AND id=:id",
                           symbol=symbol, id=session["user_id"])
    total_share = share_qty[0]["shares"]

    # Check if user has enough shares of the stock
    if total_share < shares:
        return apology("You don't have enough stocks")
    else:
        # Calcalute how much cash user now has
        new_cash = float(cash[0]["cash"]) + total

        # Log in updated cash
        db.execute("UPDATE users SET cash=:new_cash WHERE id=:id",
                           new_cash=new_cash, id=session["user_id"])

        # Insert into hisotry table to record the transaction
        db.execute("INSERT INTO history (symbol, shares, price, id) VALUES (:symbol, :shares, :price, :id)",
                           symbol=symbol, shares=shares, price=price, id=session["user_id"])

        # Updating portfolio table reflecting the sell of shares
        if total_share == shares:
            db.execute("DELETE FROM portfolio WHERE symbol=:symbol AND id=:id",
                               symbol=symbol, id=session["user_id"])
        else:
            new_total = total_share - shares
            db.execute("UPDATE portfolio SET shares=:new_share WHERE id=:id",
                                new_share=new_total, id=session["user_id"])

        # Flash sold alert
        flash('Sold!')

        # Redirect to index page
        return redirect("/")

 # If request method GET
 else:
    return render_template("sell.html", cash=cash[0]["cash"], stocks=stocks)

............................................................................

I want to use the backend python code above with my frontend sell.html code which is as follows:

{% extends "layout.html" %}

{% block title %}
    Sell
{% endblock %}

{% block main %}
    <form action="/sell" method="post">
        <div class="form-group">
            <select  class="form-control" name="symbol" placeholder="Symbol">
                {% for stock in stocks %}
                <option value ="{{stock.symbol}}" > {{ stock.symbol}} </option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group">
            <input autocomplete="off" class="form-control" min="0" name="shares" placeholder="Shares" type="number">
        </div>
        <button class="btn btn-primary" type="submit">Sell</button>
    </form>
{% endblock %}

Issue: Unable to get the output or the dropdown list of bought share in my portfolio.