8- Forms in Flask
Play this article
Create “form.html” file that contains a form to answer a question: “What is the most popular programming language?” and three fields for answers:
<form action = "http://localhost:5000/result" method = "POST">
<p>What is the most popular programming languages?</p>
<p>First <input type = "text" name = "First popular" /></p>
<p>Second <input type = "text" name = "Second popular" /></p>
<p>Third <input type = "text" name = "Third popular" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
And create a “results.html” file to return results:
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
And now prepare a “form.py” script:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('form.html')
@app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
return render_template("results.html",result = result)
if __name__ == '__main__':
app.run(debug = True)
Run the Python script and the following page should be opened:
Fill out the form and submit it to get the results page like this:
* If you like the content, please SUBSCRIBE to my channel for the future content