I'm trying to empower users to deposit/withdraw cash, and I would like to be able to do this all on one page. I created two radio buttons that the user can check to decide if they want to deposit or to withdraw, but I'm having a hard time checking if any button is checked at all, but also to know whether I should deposit or withdraw the amount and update their cash accordingly.
When I looked up this question I found a lot of ways to do this in javascript but I couldn't find any in python except maybe this which I have tried to follow, but it doesn't seem to be working for me. My two problems are:
1) Whether I click deposit or withdraw, it ends up subtracting in the amount entered in the users account.
2) If I select neither radio button, my code does not catch this and instead crashes.
How can I check for these?
deposit method (handles deposit and withdraw):
@app.route("/deposit", methods=["GET", "POST"])
@login_required
def deposit():
"""Update cash amount."""
# check if user is submitting
if request.method == "POST":
# make sure user provides an amount
if not request.form.get("amount"):
return apology("must provide amount")
# make sure amount is valid
if (request.form.get("amount").isalpha() or float(request.form.get("amount")) <= 0):
return apology("invalid amount")
amount = request.form.get("amount")
option = request.form["option"]
# try to check if no radio button was pressed
if not option:
return apology("must choose deposit or withraw")
# depositing cash adds amount, withdrawing subtracs amount
if option == deposit:
db.execute("UPDATE users SET cash = cash + :amount WHERE id = :userId", amount = amount, userId = session["user_id"])
else:
db.execute("UPDATE users SET cash = cash - :amount WHERE id = :userId", amount = amount, userId = session["user_id"])
# redirect user to home page
return redirect(url_for("index"))
else:
return render_template("deposit.html")
deposit.html:
{% extends "layout.html" %}
{% block title %}
Deposit
{% endblock %}
{% block main %}
<form action="{{ url_for('deposit') }}" method="post">
<fieldset>
<!-- makes two readio buttons with different values so I can know which the user picked -->
<div class="form-group">
<input type="radio" name="option" value="deposit"> Deposit
</div>
<div class="form-group">
<input type="radio" name="option" value="withdraw"> Withdraw
</div>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="amount" placeholder="Amount ($)" type="float"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="quote">Confirm</button>
</div>
</fieldset>
</form>
{% endblock %}