Wtforms表单,用于访问嵌入表单字段的语法

时间:2013-06-28 12:41:02

标签: python flask wtforms

尝试填充Wtform表单字段,将数据拉出mongo db数据库,然后将其提供给jinja / flask,为我正在构建的REST系统创建可编辑的预填充表单。

我的表单结构:

class ProjectForm(Form):
    name = TextField("Name of Project")     
    workflow =FieldList(TextField(""), min_entries=5)

class InstituteForm(Form):
    institue_name = TextField("Name of Institue")
    email = FieldList(TextField(""), min_entries=3)
    project_name = FormField(ProjectForm)
    submit = SubmitField("Send")`

我可以使用以下语法预先填充我的字段列表:

form = InstituteForm(institue_name="cambridge",
                     email=["email@gmail", "email@gmail"])

但是,我无法弄清楚预先填充包含表单对象的FormField的语法。

首先,我创建一个项目表单:

p = ProjectForm(name=" test", workflow=["adadadad", "adasdasd", "adasdadas"])

&安培;现在我正在尝试将其添加到InstituteForm表单中。

我试过了:

form = InstituteForm(institue_name=store_i,
                     project_name=p,
                     email=store_email)

我获得了html输出:

上传的示例输出[http://tinypic.com/r/jpfz9l/5],没有足够的点来将图像发布到堆栈溢出。

我尝试过语法:

form = InstituteForm(institue_name=store_i,
                     project_name.name=p,
                     email=store_email)

form = InstituteForm(institue_name=store_i,
                     project_name=p.name,
                     email=store_email)

甚至

form = InstituteForm(institue_name=store_i,
                     project_name=ProjectForm(name="this is a test"),
                     email=store_email)

搜索并找到了另一个类似问题的线程(没有回复):

Using FieldList and FormField

1 个答案:

答案 0 :(得分:2)

project_name can be dict or object(不是表单对象,因为它会使用html标记值填充InstituteForm.project_name),因此您可以使用下一个代码:

form = InstituteForm(institue_name="cambridge",
                     project_name=dict(name="test name"),
                     email=["email@gmail", "email@gmail"])

class Project(object):
    name = "test"
    workflow = ["test1", "test2"]

form = InstituteForm(institue_name="cambridge",
                     project_name=Project(),
                     email=["email@gmail", "email@gmail"])

class Project(object):
    name = "test"
    workflow = ["test1", "test2"]

class Institute(object):
    institue_name = "cambridge"
    project_name = Project()
    email = ["email@gmail", "email@gmail"]

form = InstituteForm(obj=Institute())

此示例等效,因为WTForms使用带有obj参数的构造函数和**kwargs,这些示例的工作方式类似。

相关问题