简体   繁体   English

使用Flask和Flask-MongoAlchemy时的WTForms语法

[英]WTForms syntax when using Flask and Flask-MongoAlchemy

I am testing out Python framework Flask and Flask-MongoAlchemy with MongoDB (of course). 我正在用MongoDB测试Python框架Flask和Flask-MongoAlchemy (当然)。 As I'm building multiple documents in my test app, I like to get the forms validated us WTForms . 在测试应用程序中构建多个文档时,我希望通过WTForms验证表单

Can anyone share with me an example on how to create the object references in a SelectField()? 谁能和我分享一个如何在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! 谢谢!

It's documented in WTForms documentation of the SelectField quoted here for convenience: 为方便起见,在此处引用的SelectField的WTForms文档中对此进行了记录

Select fields keep a choices property which is a sequence of (value, label) pairs. 选择字段保留一个choices属性,该属性是(值,标签)对的序列。

I'm not sure about form.parent.choices syntax but the code looks like: 我不确定form.parent.choices语法,但是代码如下:

form.parent.choices = [(1, 'parent name 1'), (2, 'parent name 2'), (3, 'parent name 3'), (4, 'parent name 4')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM