I'm trying to post output on a web page based on user input using HTML and Flask. Given below are the codes.
app.py :
import pandas as pd
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
x_in = request.form.get('x_in')
elif request.method == 'GET':
data = pd.DataFrame({'data':[int(x_in)*10]})
return render_template('index.html', data=data.to_html())
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=False)
I have used the following 2 html files for rendering.
template.html:
html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Flask Parent Template</title>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Trial</h1>
<strong><nav>
<ul class="menu">
<li><a href="{{ url_for('predict') }}">Home</a></li>
</ul>
</nav></strong>
</div>
</header>
{% block content %}
{% endblock %}
</body>
</html>
index.html:
html>
<title>About the App</title>
<head>
<body>
{% extends "template.html" %}
{% block content %}
<form action = / method="POST">
<label for="x_in">INPUT:</label>
<input type="text" name="x_in" id="x_in" size="15">
<input type="submit" value="Generate Result" />
</form>
{{data|safe}}
{% endblock %}
</body>
</html>
However, I am getting an error as follows : UnboundLocalError: local variable 'x_in' referenced before assignment
This is a very simple code and I am not sure why the 'POST' method isn't receiving the input from user. My guess is it's a trivial error but any help would be appreciated.
According to me you want to show a input form and user enter imput and get result
@app.route('/', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
x_in = request.form.get('x_in')
data = pd.DataFrame({'data':[int(x_in)*10]})
return render_template('index.html', data=data.to_html())
return render_template("index.html")
in jinja do this
{% if data %}
{{data|safe}}
{% endif %}