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)

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

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

            shares = request.form.get("shares")

            # query database for user's cash
            cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
            cash = cash[0]["cash"]

            # select the symbol shares of that user
            user_shares = db.execute("SELECT shares FROM portfolio WHERE id = :id AND symbol=:symbol", \
                                 id=session["user_id"], symbol=stock["symbol"])

            stocks = db.execute("SELECT shares, symbol FROM portfolio WHERE id=:id", id=session["user_id"])

            # check if enough shares to sell
            if user_shares[0]["shares"] < shares:
                return apology("Too many shares")

            # update  of a sell
            db.execute("INSERT INTO history (symbol, shares, price, id) \
                    VALUES(:symbol, :shares, :price, :id)", \
                    symbol=stock["symbol"], shares=-shares, \
                    price=usd(stock["price"]), id=session["user_id"])

            # update user cash (increase)
            db.execute("UPDATE users SET cash = cash + :cash_after WHERE id = :id", \
                    id=session["user_id"], \
                    cash_after=stock["price"] * float(shares))

            # decrement the shares count
            shares_total = user_shares[0]["shares"] - shares

            # if after decrement is zero, delete shares from portfolio
            if shares_total == 0:
                db.execute("DELETE FROM portfolio \
                        WHERE id=:id AND symbol=:symbol", \
                        id=session["user_id"], \
            # otherwise, update portfolio shares count
                db.execute("UPDATE portfolio SET shares=:shares \
                    WHERE id=:id AND symbol=:symbol", \
                    shares=shares_total, id=session["user_id"], \

            # flash bought alert

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

        # If request method GET
        return render_template("sell.html", 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 %}
{% 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 %}
        <div class="form-group">
            <input autocomplete="off" class="form-control" min="0" name="shares" placeholder="Shares" type="number">
        <button class="btn btn-primary" type="submit">Sell</button>
{% endblock %}

Issue: Unable to get the output or the dropdown list of bought share in my portfolio. I get a stack trace. enter image description here


Your options also need a value. Like value="{{ stock.symbol }}".

I also put the number of owned shares and IIRC current price per share into the text (but not into the value), that's my personal preference.

| improve this answer | |
  • Thanks! I tried by adding a value in my sell.html <option value="{{stock.symbol}}" > {{ stock.symbol}} </option>. However I still get an error when I click on the SELL option. It says - "Internal Server Error". Do you think it is the for loop within my application.py which could be causing error? I used similar trick and it worked for index but not working here. – Aakash May 9 '18 at 9:07
  • You should get a stack trace in the terminal where you flask run, pointing you to the source. Oh, and I think you have to use {% and not { % – Blauelf May 9 '18 at 9:16
  • Wait - you pass "cash" and "symbols", and in your template use "stocks". Something tells me that this won't work. – Blauelf May 9 '18 at 9:21
  • I fixed '{%' in my template and also replaced symbols with stocks in my application.py but it is still giving me a stack trace - – Aakash May 9 '18 at 10:48
  • The stack traceback : .. "POST /login HTTP/1.1" 302 DEBUG:cs50:SELECT shares, symbol FROM portfolio WHERE id = 1 DEBUG:cs50:SELECT cash FROM users WHERE id=1 DEBUG:cs50:SELECT * from portfolio WHERE id=1 INFO:werkzeug: - - "GET / HTTP/1.1" 200 - INFO:werkzeug: - - "GET /static/styles.css HTTP/1.1" 200 - [2018-05-09 10:20:34,698] ERROR in app: Exception on /sell [GET] Traceback (most recent call last): File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() – Aakash May 9 '18 at 10:49

You must log in to answer this question.

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