Handling HTML forms with the POST method in Flask app using Python

Posted by


Handling HTML form with POST method in a Flask app in Python is a common task for web developers. In this tutorial, we will walk you through the steps to handle a simple HTML form using the POST method in a Flask app.

Step 1: Set up a Flask app
First, make sure you have Flask installed. If you don’t have Flask installed, you can install it using pip:

pip install Flask

Next, create a new Python file (e.g., app.py) and import the Flask module:

from flask import Flask, render_template, request

Then, create a new instance of the Flask class:

app = Flask(__name__)

Step 2: Create a route for the form
In your Flask app, create a route for the form. In this example, we will create a simple form that accepts a name and an email address.

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        return f'Hello {name}, your email is {email}'
    return render_template('form.html')

Step 3: Create an HTML form
Next, create an HTML file (e.g., form.html) in a templates folder in the same directory as your Python file. Add the following code for the form:

<!DOCTYPE html>
<html>
<head>
    <title>Flask Form</title>
</head>
<body>
    <h1>Enter your name and email:</h1>
    <form method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        <br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Step 4: Run the Flask app
Finally, run your Flask app by adding the following code at the end of your Python file:

if __name__ == '__main__':
    app.run(debug=True)

Now you can run your Flask app by navigating to the directory where your Python file is located and running the following command:

python app.py

You should see a message indicating that your Flask app is running. Open a web browser and go to http://127.0.0.1:5000/ to see your form. Fill in the form with your name and email address and submit it.

Congratulations! You have successfully handled an HTML form with the POST method in a Flask app in Python. You can expand on this example by adding more fields to the form or by implementing additional functionality, such as form validation or storing form submissions in a database.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x