Open In App

Retrieving HTML Form data using Flask

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Read this article to know more about Flask Create form as HTML 



We will create a simple HTML Form, very simple Login form




<form action="{{ url_for("gfg")}}" method="post">
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="fname" placeholder="firstname">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lname" placeholder="lastname">
<button type="submit">Login</button>

Its an simple HTML form using the post method the only thing is unique is action URL. URL_for is an Flask way of creating dynamic URLs where the first arguments refers to the function of that specific route in flask. In our form it will create a Dynamic route which has gfg function in the flask app



Create Flask application

Start your virtual environment

pip install virtualenv
python3 -m venv env
pip install flask

Now we will create the flask backend which will get user input from HTML form




# importing Flask and other modules
from flask import Flask, request, render_template
 
# Flask constructor
app = Flask(__name__)  
 
# A decorator used to tell the application
# which URL is associated function
@app.route('/', methods =["GET", "POST"])
def gfg():
    if request.method == "POST":
       # getting input with name = fname in HTML form
       first_name = request.form.get("fname")
       # getting input with name = lname in HTML form
       last_name = request.form.get("lname")
       return "Your name is "+first_name + last_name
    return render_template("form.html")
 
if __name__=='__main__':
   app.run()

Working – 

Almost everything is simple, We have created a simple Flask app, if we look into code

Output – Code in action flask server running html form returning data from html template


Article Tags :