在Flask和Flask-MongoAlchemy中使用WTForms语法

1 投票
1 回答
1431 浏览
提问于 2025-04-17 04:47

我正在测试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?

任何建议都非常好!或者提供一个在线示例的链接。谢谢!

1 个回答

1

在这里引用了WTForms的SelectField文档,方便大家查看:

选择字段会保存一个叫做choices的属性,这个属性是一个(value, label)对的序列。

我不太确定form.parent.choices的写法,但代码大概是这样的:

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

撰写回答