gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:47 28 4
gpt4 key购买 nike

我正在使用 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?

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

最佳答案

它记录在WTForms documentation of the SelectField中为了方便起见,在此引用:

Select fields keep a choices property which is a sequence of (value, label) pairs.

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

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

关于python - 使用 Flask 和 Flask-MongoAlchemy 时的 WTForms 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7856949/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com