3

I have an HTML form that accepts an arbitrary number of books and their authors. I'm trying to group the corresponding books and authors so that it's easily parsed by the server when the user submits the form. I tried using the HTML fieldset, but I'm not certain if that's the right approach.

When I submit the form to the server there's no notion of the fieldset in Flask's request.form

Here's the HTML form:

<form action="/save/" method="POST">

    <fieldset>
        <input name="author" value="Mark Twain" class="author" type="text">
        <input name="book" value="The Adventures of Tom Sawyer" class="book" type="text">        
    </fieldset>

    <fieldset>
        <input name="author" value="Henry David Thoreau" class="author" type="text">
        <input name="book" value="Civil Disobedience" class="book" type="text">        
    </fieldset>

    <!--More books and authors here possibly-->

    <button type="submit">Save</button>

</form>

And here's what I see on the server when I log request.form:

ImmutableMultiDict([('book', u'The Adventures of Tom Sawyer'), ('book', u'Civil Disobedience'), ('author', u'Mark Twain'), ('author', u'Henry David Thoreau')])

You can see that the data the server receives has no notion of the fieldset or grouping of any sort.

Is there a better way to group the individual books with their corresponding authors? I'd prefer to do all of this in HTML rather than involve jQuery/JSON/AJAX.

Raj
  • 3,791
  • 5
  • 43
  • 56

1 Answers1

3

No, unfortunately this is not possible. The only data that's submitted for a field is its name and value. And while the way Flask handles form data (the name does not affect the handling) is generally better than in PHP (where a name like author[some_id] would create an array) this is one of the few cases you need to handle manually.

The easiest way would be using names like author-ID and title-ID and then iterate over the fields, extracting the ID and actual name from the key.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Do you have any suggestions on how I can maintain order of the books as the server sees them? I can use the method that you suggest, but the order of the books/authors is not maintained when I log request.form. – Raj Oct 01 '13 at 13:39
  • You can't. The data is stored in a MultiDict and like all dicts they do not preserve order. It's not a good idea to rely on the field order anyway. – ThiefMaster Oct 01 '13 at 13:48
  • 3
    Actually @Raj it is possible to preserve the order, you just have to use [`ImmutableOrderedMultiDict`](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.ImmutableOrderedMultiDict) as the backing store for your [`request_class`](http://flask.pocoo.org/docs/api/#flask.Flask.request_class). See [this answer](http://stackoverflow.com/a/18189963/135978) for more details – Sean Vieira Oct 02 '13 at 00:42