Reputation: 361
I am testing out Python framework Flask and Flask-MongoAlchemy with MongoDB (of course). As I'm building multiple documents in my test app, I like to get the forms validated us WTForms.
Can anyone share with me an example on how to create the object references in a SelectField()?
class Parent(db.Document):
title = db.StringField()
description = db.StringField()
class Object(db.Document):
parent = db.DocumentField(Parent)
title = db.StringField()
@app.route('/object/new', methods=['GET', 'POST'])
def new_object():
form = ObjectForm(obj=Object)
form.parent.choices = [(???) for p in Parent.query.all()] #<-- #1 correct syntax I like to understand, '(t._id, t.title)' didn't work.
if form.validate_on_submit():
form.save()
return redirect(url_for('...'))
return ....
class ObjectForm(wtf.Form):
parent = wtf.SelectField(u'Parent') #<-- #2 do I need to add anything special?
Any suggestion would be great! Or link to an online example. Thanks!
Upvotes: 1
Views: 1434
Reputation: 7883
It's documented in WTForms documentation of the SelectField quoted here for convenience:
Select fields keep a choices property which is a sequence of (value, label) pairs.
I'm not sure about form.parent.choices
syntax but the code looks like:
form.parent.choices = [(1, 'parent name 1'), (2, 'parent name 2'), (3, 'parent name 3'), (4, 'parent name 4')]
Upvotes: 1