Skip to content

Building the Form

You have already learned HTML forms. Now you are going to build one that actually does something — it will collect a name, an age, and a gender, send that data to Flask, and the page will update to show the new entry.

No JavaScript. No styling. Just a plain form and Python.


What the form needs

Three fields:

  • Name — a text input
  • Age — a number input
  • Gender — a select dropdown with two options: 1 for Male, 2 for Female

And one submit button.


The form HTML

<form action="/add" method="post">

    <label for="name">Name</label>
    <input type="text" id="name" name="name" placeholder="Full name">

    <label for="age">Age</label>
    <input type="number" id="age" name="age" placeholder="Age">

    <label for="gender">Gender</label>
    <select id="gender" name="gender">
        <option value="1">Male</option>
        <option value="2">Female</option>
    </select>

    <button type="submit">Add Person</button>

</form>

Two things to notice:

  • action="/add" — when the user clicks Submit, the data goes to the /add route in Flask
  • method="post" — the data is sent as a POST request, not visible in the URL

The name attributes (name="name", name="age", name="gender") are what Flask uses to find each value. You will see this in the next page.


The full index.html so far

This page will show the form at the top and the table of people below it:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>People</title>
  </head>
  <body>

    <h1>Add a Person</h1>

    <form action="/add" method="post">

        <label for="name">Name</label>
        <input type="text" id="name" name="name" placeholder="Full name">

        <label for="age">Age</label>
        <input type="number" id="age" name="age" placeholder="Age">

        <label for="gender">Gender</label>
        <select id="gender" name="gender">
            <option value="1">Male</option>
            <option value="2">Female</option>
        </select>

        <button type="submit">Add Person</button>

    </form>

    <h2>People so far</h2>

    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
          <th>Gender</th>
        </tr>
      </thead>
      <tbody>
        {% for person in people %}
        <tr>
          <td>{{ person.name }}</td>
          <td>{{ person.age }}</td>
          <td>{% if person.gender == 1 %}Male{% else %}Female{% endif %}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>

  </body>
</html>

The table is already there waiting — it will be empty at first and fill up as people are added.


Challenge

Put this HTML into templates/index.html. Open the app in your browser. The form should appear, and below it an empty table with just the headers. You cannot submit it yet — Flask does not have the /add route. That is next.


← Displaying a Table    Next: Receiving Data in Flask →