【问题标题】:WTForms syntax when using Flask and Flask-MongoAlchemy使用 Flask 和 Flask-MongoAlchemy 时的 WTForms 语法
【发布时间】:2011-10-22 02:04:53
【问题描述】:

我正在测试 Python 框架 Flask 和 Flask-MongoAlchemy 与 MongoDB(当然)。当我在我的测试应用程序中构建多个文档时,我喜欢让表单验证我们 WTForms

谁能与我分享一个如何在 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?

任何建议都会很棒!或链接到在线示例。谢谢!

【问题讨论】:

    标签: python mongodb flask wtforms


    【解决方案1】:

    为方便起见,此处引用的WTForms documentation of the SelectField 中有记录:

    选择字段保留一个选择属性,该属性是(值, 标签)对。

    我不确定form.parent.choices 的语法,但代码如下:

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

    【讨论】:

    • 在我的情况下,父表将有 100 多个项目。到目前为止在线示例仅适用于 sqlalchemy / 最流行的 SQL DB,但不适用于 mongoDB。如果你发现了什么,请告诉我。我会继续寻找。
    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多