Python WTForms:如何在FormFields的FieldList中动态设置SelectField的选项?

问题描述 投票:2回答:1

我目前正在尝试使用WTFormsFieldListFormField附件,以允许用户添加具有相应覆盖量的自定义位置子集。

表单向用户显示一些标准输入,然后使用单个字段集(FormField)进行初始化,每个字段具有位置选择输入和覆盖量输入。

Javascript允许用户根据需要添加或删除其他位置覆盖字段集以反映准确的文档信息。

问题:作为一种解决方法,我一直通过在表单处理程序的GET请求中传递模板变量并手动创建自己的表单字段来设置位置选项。这不是更新实际的WTForms位置字段选项,因此当我提交表单时,会为位置字段引发异常(“不是有效选择”)。

当我实例化location时,如何动态地将位置选择添加到LocationForm的MyForm字段?

这基本上是我的代码的样子:

注意:我省略了在GET请求中创建位置模板变量的代码,因为这不是所需的设计。我希望更符合预期的WTForms方法:

class LocationForm(Form):
    location = SelectField('Location', [], choices=[])
    coverage = FloatField('Coverage', [])

class MyForm(BaseForm):
    # other fields omitted for brevity
    location_coverage = FieldList(FormField(LocationForm), [], min_entries=1)

class AddDocument(BaseHandler):

    def get(self):
        params = {
           "cid": cid
        }
        return self.render_template("form.html", **params)

    def post(self):
        cid = self.request.get('cid')
        if not self.form.validate():
            return self.get()
        company_key = ndb.Key('Company', cid)
        doc = Document(parent=company_key)
        self.form.populate_obj(doc)
        doc.put()
        params = { 
            "cid": 
        }
        return self.redirect_to('view_company', **params)

    @webapp2.cached_property
    def form(self):
        f = MyForm(self)

        # HERE is where I would normally do something like:
        # company = ndb.Key('Company', int(self.request.get('cid')))
        # locations = ndb.Location.query(ancestor=company).fetch() 
        # f.field_name.choices = [(loc.key, loc.name) for loc in locations]
        # but this doesn't work with Select Fields enclosed in 
        # FormFields and FieldLists.

        return f

编辑:

我创建了一个解决方案,但这不是我要找的答案。在我的例子中,我只是将LocationForm.location表单字段从SelectField更改为StringField。这样做会绕过选择字段选项的验证并允许表单提交。这不是理想的,因为它不是预期的设计,但如果有人能够引导我在这个特定场景中使用WTForms更合适的方式,我将非常感激。

python google-app-engine jinja2 app-engine-ndb wtforms
1个回答
0
投票

如果您的BaseForm类从实例化的post数据填充表单,您应该看到嵌套表单填充在您通常将选项直接添加到表单上的SelectField中的位置。

因此,像:

for entry in f.location_coverage.entries:
    entry.location.choices = [(loc.key, loc.name) for loc in locations]

应该将选项填充到每个子表单选择字段中。

© www.soinside.com 2019 - 2024. All rights reserved.