I am new to programming. I am interested in developing a simple web app with two input values and two submit buttons. Numbers A and B are input by users and the product OR the sum will be shown depending on which button is pressed. When I use one button, the code works; however, I can't seem to figure out how to make both buttons work. I wrote the application in Flask and Python 3.8 and used wtforms.
Here are my codes: view.html
<table>
{% for field in form %}
<tr>
<td>{{ field.name }}</td><td>{{ field }}</td>
<td>{{ field.label }}</td>
</tr>
{% endfor %}
</table>
<form method="post" action="">
<input type="submit" name="btn" value="Add">
</form>
<p>
<form method="post" action="">
<input type="submit" name="btn" value="Multiply">
</form></p>
<p>
{% if result != None %}
{{result}}
{% endif %}
</p>
Python code views.py
@app.route("/comp", methods=['GET', 'POST'])
def comp():
form = InputForm(request.form)
if request.method == 'POST' and form.validate():
if request.form["btn"] == "Add":
result = add(form.A.data, form.B.data)
elif request.form["btn"] == "Multiply":
result = mul(form.A.data, form.B.data)
else: result = None
return render_template('view.html', form=form, result=result)
I defined mul() and add() functions in a separate file, as I plan to expand the application further in the future. Here is the function definition:
def mul(A,B):
return A*B
def add(A,B):
return A+B
My input.py file:
from wtforms import Form, FloatField, validators
class InputForm(Form):
A = FloatField(
label='A', default=0,
validators=[validators.InputRequired()])
B = FloatField(
label='B', default=0,
validators=[validators.InputRequired()])