I am new to Flask and I'm trying to build a simple web app. Basically what I have on the home page is a text input box and a submit button. After clicking submit, it shows some result based on the text that was inputted (for now it's hardcoded in the code below).
What I want is when you click submit, it should not only show the result but also a button to add the inputted text to a specific file. However, I am struggling to get this to work (the "Add to dataset" button doesn't do anything).
Here is what I have for now:
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
# if submit button is clicked
if request.form['submit'] == 'Submit':
# get the text from the form that was filled in
input_text = request.form['text']
final_result = 'stackoverflow rocks'
return render_template('index.html', result=final_result, text=input_text)
if request.form['add-dataset'] == 'Add to dataset':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text)
The index.html:
<!doctype html>
<head>
<link rel="stylesheet" media="screen" href ="static/bootstrap.min.css">
<link rel="stylesheet" href="static/bootstrap-theme.min.css">
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
</head>
<br/>
<div class="container">
<form action="/" method="post" role="form">
<div class="form-group">
<label for="text">Text:</label>
<input type="text" class="form-control" name="text" placeholder="Input sentence here">
<br />
</div>
<input type="submit" name="submit" value="Submit" class="btn btn-success">
</form>
<br/>
{% if result is not none %}
<div class="alert alert-success">
{{ result }}
</div>
<h2>Add to dataset</h2>
<br/><input type="submit" name="add-dataset" value="Add to dataset" class="btn btn-success">
{% endif %}
</div>
</html>