DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

8- Create forms in Flask

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Run the Python script and the following page should be opened:

Image description

Fill out the form and submit it to get the results page like this:

Image description

* If you like the content, please SUBSCRIBE to my channel for the future content

Top comments (2)

Collapse
 
vulcanwm profile image
Medea

it's nice to see other people making flask form tutorials!

Collapse
 
azad77 profile image
Dr. Azad Rasul

Thank you for your comment!