In this tutorial we will learn that how to handle a user input in flask web app. our goal is to let users submit their name and email through a form. Here when the user submits the form first the app will check if the input are valid -note that fields should not be empty ,then verify the email is correctly formatted using Flask’s function. If the input invalid then the app will show error message using Flask’s flash() function. If everything is fine the app will save data in database for future use.
The user is redirected to a confirmation page after submission to prevent resubmission. This process helps in building dynamic and interactive applications that respond to user input efficiently.
Handling a user input in flaskweb app
- Python flask app: user input (name & email)
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): message = '' if request.method == 'POST': name = request.form.get('name') email = request.form.get('email') if not name or not email: message = "Please fill in both name and email." elif '@' not in email: message = "Please enter a valid email address." else: message = f"Hello, {name}! We have received your email: {email}" return render_template('form.html', message=message) if __name__ == '__main__': app.run(debug=True)
- HTML Template : user input form
<!DOCTYPE html> <html> <head> <title>User Form</title> </head> <body> <h2>User Information Form</h2> <form method="POST"> <label>Name:</label> <input type="text" name="name" placeholder="Enter your name"><br><br> <label>Email:</label> <input type="email" name="email" placeholder="Enter your email"><br><br> <button type="submit">Submit</button> </form> {% if message %} <p style="margin-top:20px; font-weight:bold;">{{ message }}</p> {% endif %} </body> </html>
The user has to enter name and email and if the user leaves a field empty error message will show lets see with example.
Output example :
- Name : basha
- Email : [email protected]
The message shown will be:
Hello, basha! We have received your email: [email protected]
If the user leaves fields empty or gives an invalid email, an error message will be shown.