Flask Forms and User Input Tutorial

Flask Forms and User Input Tutorial | DarchumsTech

Flask Tutorial Part 2: Handling Forms and User Input

by DarchumsTech

✍️ What Are Forms?

Forms are used in websites to collect user input like names, emails, or messages. In Flask, we handle them using the POST method and the request object.

🔧 Sample Form in Flask

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        name = request.form['name']
        return f"Hello, {name}!"
    return '''
        <form method="POST">
            Enter your name: <input type="text" name="name">
            <input type="submit" value="Submit">
        </form>
    '''

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

Save this as app.py and run it. Visit http://127.0.0.1:5000/ in your browser.

🧠 Explanation

  • methods=['GET', 'POST'] allows form submission using POST.
  • request.form gets data submitted by the user.
  • We return a personalized message based on input.

🔐 Security Tip

Never trust user input blindly. Always validate and sanitize inputs when handling real-world applications!

📌 Summary

  • 📤 HTML forms let users submit data
  • 📬 Flask uses request.form to handle POST data
  • 🔁 You can return responses based on user input

© 2025 DarchumsTech. All rights reserved.

Comments