Home > Software design >  form.getlist() not working on htmx expanded form?
form.getlist() not working on htmx expanded form?

Time:05-13

I have an order form in a flask-based app. The form starts out with a single row for the user to fill out with the name of a product, etc.

Then there is an Add Item button which sends an htmx request. It can be used to add an indefinite number of additional rows.

Here is the code:

<table  >
<thead >
    <tr>
    <th>Product Name</th>
    <th>Unit</th>
    <th>Quantity</th>
    </tr>
</thead>

<form autocomplete="off" action="/neworder" method="POST">
    <tr>
    <td><input type="text" name="product" ></td>
    <td><input type="text" name="unit"></td>
    <td><input type="text" name="number_of_units"></td>
    </tr>

    <tr hx-target="this">
    <td><button type="button" hx-get="/adminorder" hx-swap="outerHTML" >Add Item</button></td>
    </tr>
</tbody>
</table>
   
<p>Order Date:  <input type="text" name="date"></p>
<input type="submit">
</form>

htmx returns this:

<tr>
<td><input type="text" name="product"></td>
<td><input type="text" name="unit"></td>
<td><input type="text" name="number_of_units" ></td>
</tr>

<tr hx-target="this">
<td><button type="button" hx-get="/adminorder" hx-swap="outerHTML" >Add Item</button></td>
</tr>

As you see, all the inputs in a column have the same name.

When the form is submitted, I want to use flask request to do this:

@app.route('/neworder', methods=["POST"])
def new_order():
    ...
    order_date = request.form.get("date")
    items = request.form.getlist("product")
    return f'<html>{order_date} - {items}</html>'

However, the only thing that ends up in items is what was entered into the first row... I tried starting out with more than one row, and then things worked as expected, so it must have something to do with the part of the code returned by htmx...

I don't think this is relevant (?) but the function used by hx-get looks simply like this:

@app.route('/adminorder')
def admin_order():
    return render_template('adminorder.html')

CodePudding user response:

Your HTML template is invalid, you should move the form opening tag outside of the table. I've also added a missing <tbody> tag.

<form autocomplete="off" action="/neworder" method="POST">
<table  >
<thead >
    <tr>
    <th>Product Name</th>
    <th>Unit</th>
    <th>Quantity</th>
    </tr>
</thead>

<tbody>
    <tr>
    <td><input type="text" name="product" ></td>
    <td><input type="text" name="unit"></td>
    <td><input type="text" name="number_of_units"></td>
    </tr>

    <tr hx-target="this">
    <td><button type="button" hx-get="/adminorder" hx-swap="outerHTML" >Add Item</button></td>
    </tr>
</tbody>
</table>
   
<p>Order Date:  <input type="text" name="date"></p>
<input type="submit">
</form>
  • Related