0
0
Flaskframework~5 mins

Accessing form data in Flask

Choose your learning style9 modes available
Introduction

We use form data to get information users type into a web form. Accessing this data lets our app respond to user input.

When a user submits a login form with username and password.
When collecting feedback from a contact form on a website.
When processing search queries entered by users.
When users fill out a registration form to create an account.
Syntax
Flask
from flask import request

@app.route('/submit', methods=['POST'])
def submit():
    value = request.form['field_name']

request.form holds the form data sent by the user.

You access each form field by its name attribute.

Examples
Get the value of the form field named 'username'.
Flask
username = request.form['username']
Get 'email' field value or use a default if missing.
Flask
email = request.form.get('email', 'no-email@example.com')
Convert all form data into a Python dictionary.
Flask
all_data = request.form.to_dict()
Sample Program

This Flask app shows a simple form asking for a name. When submitted, it reads the name from the form data and greets the user.

Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def form():
    return '''
    <form method="POST" action="/submit">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name">
      <button type="submit">Send</button>
    </form>
    '''

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'Hello, {name}! Your form was received.'

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

Always check the HTTP method is POST before accessing form data.

Use request.form.get() to avoid errors if a field is missing.

Form field names must match the keys you use to access data.

Summary

Use request.form to get data sent by a form.

Access fields by their name attribute.

Handle missing fields safely with get().