I'm learning Flask now. Trying to achieve the calculation result to be displayed on the same page as the input fields, but also based on the button activated ("+" or "-") by the user before hitting the "result" button.
I'm getting the following error:
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
I tried following recommendations on Flask Python buttons, but those seem to only be working when redirecting to a new page.
a piece of app.py:
@app.route('/calculate', methods=['GET', 'POST'])
def calculate():
form = InputForm(request.form)
if request.method == 'POST' and form.validate():
if "+" in request.form:
result = Percentage.function1(form.x.data, form.y.data)
elif "-" in request.form:
result = Percentage.function2(form.x.data, form.y.data)
else:
result = None
return render_template('calc.html',
form=form, result=result)
percentage.py:
class Percentage():
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def function1(cls, x, y):
result = round((x / (100 + y) * 100), 2)
return result
@classmethod
def function2(cls, x, y):
result = round((x * (y / 100 + 1)), 2)
return result
model.py:
from wtforms import Form, FloatField, validators
class InputForm(Form):
x = FloatField(
label='first number',
validators=[validators.InputRequired()])
y = FloatField(
label='second number',
validators=[validators.InputRequired()])
calc.html:
{% extends "base.html" %}
{% block content %}
<!DOCTYPE html>
<div class="container page-form">
<body>
<form id="calc-form" method=post action="">
<table>
{% for field in form %}
<tr>
<br>
<td>{{ field }}</td>
<td>{{ field.label }}</td>
</tr>
{% endfor %}
</table>
<br>
<p>
<a href="#" class="btn btn-primary btn-sm active" name="+" type="submit" value="+" aria-pressed="true">+</a>
<a href="#" class="btn btn-primary btn-sm active" name="-" type="submit" value="-" aria-pressed="true">-</a></p>
<br><br>
<p>
<input type=submit value=Calculate></p></form>
<p>
{% if result != None %}
<td>{{ result }}</td>
{% endif %}
</p>
</body>
</div>
{% endblock %}