0

How do I handle value(s) from a html form which is using a repeated=True property?

For example, I have this ndb.Model:

class Book(ndb.Model):
    title = ndb.StringProperty()
    genre = ndb.StringProperty(repeated = True)

With this form inside the new-book.html:

<form method="post">

    Book Title: <input type="text" name="title">
    Book Genre: <input type="text" name="genre">

    <input type="submit">

</form>

Is it appropriate to use the type="text" input? Do I ask users to "separate each genre with a comma", and then process this myself in the handler? What is the best practice for handling this type of property in html forms?

(I've asked a related question here about handling repeated StructuredProperty: Google AppEngine: Form handling 'repeated' StructuredProperty)

Community
  • 1
  • 1
hyang123
  • 1,208
  • 1
  • 13
  • 32

2 Answers2

3

A good bare-bones solution is to yes, do a comma-separated approach. Obviously not the most elegant, but it'll work.

book.genre = self.request.get("genre").split(",")

Alternatively, if you repeat the form input field, you can reuse the same input 'name' and retrieve all of the values via self.request.get_all() in your handler. (See the docs)

book.genre = self.request.get_all("genre")

My favored approach is handling data over AJAX via JSON, which would remove the need for any handling other than creating an array of values in JavaScript.

import json
form_data = json.loads(form_data)
book.genre = form_data['genre']
Josh
  • 603
  • 3
  • 16
  • When I use `self.request.get_all('genre')`, it returns the result in a list. Example: `[u'horror, comedy, romance']`. I can then split it like this: `genres = [u'horror, comedy, romance'].split(', ')`, and this returns `[u'horror', u'comedy', u'romance']`. Why is there a `u` prepending the value? I should ideally store this as `['horror', 'comedy', 'romance']` right? Sorry if this is too simple; this is my first time programming. – hyang123 Nov 22 '13 at 16:59
  • 2
    The u indicates unicode string :). Take a look at the answer here: http://stackoverflow.com/questions/11279331/what-does-the-u-symbol-mean-in-front-of-string-values . You should be fine storing it in the datastore. – iceanfire Nov 23 '13 at 03:33
1

If you know all of the possible genres beforehand then a group of checkboxes or a select box would also work well.

Smerk
  • 645
  • 6
  • 16