I'd like to allow users to buy and sell shares they already own from the index page. I've created a button for this on the index, and I simply want to send the user to the /buy.html or /sell.html page that I've created - with the share symbol already populated. The index page looks like this:
When I click the BUY button, I send the user to the page below - but I'd like the share symbol pre-populated (e.g. it would say TSLA instead of placeholder ABCD):
I think this boils down to two questions:(i) how do i send the right information back to application.py; (ii) what html attribute/setting do I need to use to pre-populate the symbol field in the buy.html form - rather than simply having it as a placeholder?
The relevant part of index.html is:
{% extends "layout.html" %}
{% block title %}
Portfolio
{% endblock %}
{% block main %}
<table>
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Number of Shares Owned</th>
<th>Total Amount Paid ($US)</th>
<th>Current Value ($US)</th>
<th>Gain/(Loss) ($US)</th>
<th>Options</th>
</tr>
{% for share in shares_owned %}
{% if share.num_shares_owned > 0 %}
<tr>
<td>{{share.symbol}}</td>
<td>{{share.name}}</td>
<td>{{share.num_shares_owned}}</td>
<td>{{share.total_cost_usd}}</td>
<td>{{share.total_asset_value_usd}}</td>
<td>{{share.gain_loss_usd}}</td>
<td>
<div class="form-group">
<button class="btn btn-default" type="submit"><a href="{{ url_for('buy', symbol ='{{share.symbol}}')}}">Buy</a></button>
<button class="btn btn-default" type="submit"><a href="{{ url_for('sell', symbol ='{{share.symbol}}')}}">Sell</a></button>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
[THE REST OF THE HTML CODE]
{% endblock %}
The relevant bit of my code for buy() in application.py is:
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock."""
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# THE BUY() METHOD
# else if user reached route via GET (as by clicking a link or via redirect)
else:
# if user reached route via GET from index - and hence is asking to buy more shares in a company he/she already owns
temp_symbol = request.form.get("symbol")
if temp_symbol is not None:
# Declare a dict called "temp"
temp = {}
# Add symbol to this dict
temp["symbol"] = temp_symbol
else:
# otherwise add "ABCD" to the dict (this will then be displayed as the placeholder)
temp = {}
temp["symbol"] = "ABCD"
return render_template("buy.html", temp = temp)
My understanding is that request.form.get("symbol") is returning None - but I don't understand why, since I thought I'd set it up in index.html such that it would return share.symbol.
I'd appreciate any help you can give!
Many thanks, Matt