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

发布于 2024-12-11 17:11:59 字数 900 浏览 0 评论 0原文

我正在使用 MongoDB 测试 Python 框架 Flask 和 Flask-MongoAlchemy(当然)。当我在测试应用程序中构建多个文档时,我希望通过 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?

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

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┈┾☆殇 2024-12-18 17:11:59

它记录在引用的 SelectField 的 WTForms 文档中为了方便起见,这里:

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

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

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

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')]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文