Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 72 ยท Forms and User Input

Handling HTML Forms

Learn how Flask receives HTML form data. Read request.form, handle GET and POST in one view, work with checkboxes and lists, and apply Post/Redirect/Get.

Forms are how visitors talk to your application: signing up, searching, posting a comment, paying for an order. In HTML, a <form> collects named fields and sends them to a URL when the user presses submit. In Flask, your job is to receive that data in a view function, decide what to do with it, and send back a sensible response.

This lesson covers the basic flow with no extra libraries: showing a form, reading request.form, handling several kinds of fields, and the Post/Redirect/Get pattern that prevents duplicate submissions. Validation (what to do when the data is wrong) gets its own lessons: manual validation and Flask-WTF. You will want to know about routes and methods and the request object first.

How a form travels

A form has two important attributes. action is the URL to send the data to (leave it out to reuse the current URL), and method is the HTTP verb: get puts the fields in the query string, post puts them in the request body. Use post whenever the submission changes something or contains private data, because GET URLs end up in history, logs and bookmarks.

HTML
<form method="post" action="/subscribe">
  <label for="email">Email</label>
  <input id="email" name="email" type="text">
  <button type="submit">Subscribe</button>
</form>

What matters to Flask is the name attribute of each field. The browser sends name=value pairs, and Flask exposes them in request.form. A field without a name is never sent. When the user presses the button, the browser encodes the body as application/x-www-form-urlencoded, for example email=ada%40example.com.

One view for GET and POST

The usual pattern is a single route that accepts both methods. GET shows the empty form, POST processes the submission:

Python A form handled by one view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at how client.post(..., data={...}) imitates a browser submission: Flask's test client encodes the dictionary as form data. Inside the view, request.method tells you which case you are in, and request.form is a dictionary-like object of the submitted fields. Prefer request.form.get("email", "") over request.form["email"]: if the key is missing, the bracket version raises 400 Bad Request automatically (a BadRequestKeyError), while .get lets you supply a default.

All values in request.form are strings. A number field sends "42", not 42, so convert it yourself and be ready for conversion to fail.

flowchart TD
    A["Request arrives<br/>at /subscribe"] --> B{"request.method"}
    B -->|GET| C["Render the empty form"]
    B -->|POST| D["Read request.form"]
    D --> E["Process the data"]
    E --> F["Respond"]

One route, two paths: the method decides whether to show the form or process it.

Many field types

Different inputs arrive in different shapes:

  • Text, password, hidden, select, textarea: one string per name.
  • Checkbox: present with its value (default on) when ticked, and absent when not. Test for presence, not for a value.
  • Several fields with the same name (a group of checkboxes, <select multiple>): use request.form.getlist("name") to get all values as a list.
  • Radio buttons: one value, or none if the user chose nothing.
  • Submit buttons: a button with a name and value is sent only when it is the one pressed, which lets one form offer several actions.
Python Checkboxes, lists and buttons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the first call the checkbox arrived, the two languages came through getlist, and age was converted to the integer 36. In the second call the unticked checkbox and the missing radio group are simply absent, and int("old") fails, which the view turns into None instead of crashing. Never trust that a field exists or has the type you expect: a browser can send exactly what you designed, but anyone with a script can send anything.

Two more handy facts. request.form.to_dict() gives a normal dictionary (first value of each name), and request.values combines the query string and the form body, though reading from form or args explicitly is clearer.

GET forms and the query string

A form with method="get" sends its fields in the URL (/search?q=flask), and you read them from request.args, not request.form. Searching and filtering use GET because the result page is safe to bookmark and share and does not change any data.

Python A GET search form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Post/Redirect/Get

Imagine a user submits an order and your POST view returns the "Thank you" page directly. If they press the browser's reload button, the browser offers to submit the form again, and the order is placed twice. The cure is the Post/Redirect/Get pattern (PRG): after a successful POST, do not render a page. Respond with a redirect, and the browser makes a fresh GET request to the result page. Reloading that page is harmless because a GET changes nothing.

sequenceDiagram
    participant B as Browser
    participant F as Flask
    B->>F: POST /comments (form data)
    F->>F: Save the comment
    F-->>B: 303 redirect to /comments
    B->>F: GET /comments
    F-->>B: 200 page listing comments
    Note over B,F: Reload now repeats only the GET

The redirect replaces the POST in the browser's history, so a reload cannot resubmit the form.

Python Post/Redirect/Get in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The POST handler never renders HTML; it appends the comment and returns redirect(...). The status 303 See Other says explicitly "now GET this other URL". The plain 302 that redirect uses by default also works in browsers, but 303 is the precise choice after a POST. follow_redirects=True makes the test client behave like a browser and fetch the new page.

A redirect also solves a second problem: the final URL no longer carries the POST. If you need to tell the user "Comment saved" on the next page, store a one-time message in the session, which is exactly what flash messages do.

PRG applies to successful submissions. When the data is invalid, re-render the form with status 200 (or 400/422) and the user's input so they can correct it, instead of redirecting. Manual validation shows that flow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A text field in a form has no name attribute. What happens when the form is submitted?

    Browsers only submit named fields. The name is the key you use in request.form.
  2. 2. What type are the values in request.form?

    Form data is plain text on the wire. Convert values yourself and handle ValueError.
  3. 3. How do you read all ticked boxes of a group that share the name 'language'?

    getlist returns every value for a repeated name. The other form calls return only the first value, and args reads the query string.
  4. 4. What problem does Post/Redirect/Get solve?

    After the POST, the redirect makes the browser load the result with a GET, so a reload repeats only the harmless GET.
  5. 5. Which method should a search form that only reads data usually use?

    GET is for safe, repeatable requests. The terms appear in the URL and are read from request.args.

Summary

  • A form sends its named fields to action using method; use POST for anything that changes data.
  • Handle GET (show) and POST (process) in one view with methods=["GET", "POST"] and request.method.
  • Read values with request.form.get(name, default); use getlist for repeated names; a missing checkbox is simply absent.
  • All form values are strings: convert and guard against bad input.
  • GET forms put fields in the URL and are read from request.args.
  • After a successful POST, redirect (status 303) to a GET page: Post/Redirect/Get.

Next: let a library check the fields for you with validation using WTForms.