Reputation: 1280
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)
Upvotes: 0
Views: 184
Reputation: 655
If you know all of the possible genres beforehand then a group of checkboxes or a select box would also work well.
Upvotes: 1
Reputation: 603
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']
Upvotes: 3