Python WTForms : How to dynamically set options of a SelectField in FieldList of FormFields?

标签 python google-app-engine jinja2 app-engine-ndb wtforms

我目前正在尝试使用 WTFormsFieldListFormField 封装,以允许用户添加具有相应覆盖范围的自定义位置子集金额。

该表单向用户提供一些标准输入,然后使用一组字段 (FormField) 进行初始化,每个字段都有一个位置选择输入和一个覆盖范围金额输入。

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

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

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

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

注意:我省略了在 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,我将不胜感激。

最佳答案

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

因此类似:

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

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

关于Python WTForms : How to dynamically set options of a SelectField in FieldList of FormFields?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23248211/

相关文章:

java - java hibernate 中的Google Cloud sql数据库连接错误

php - 在同一项目中使用 mysqli 将 App Engine 应用程序连接到 Google SQL 实例

python - jinja2.exceptions.UndefinedError - 没有属性 'favicon.ico'

Python subprocess.call 在没有 shell=True 的情况下不起作用

python - 将连续的 GPS 数据拆分为单独的旅程

google-app-engine - 寻找一种使用ajax使用angularjs将文件上传到应用程序引擎的方法

python - 如果 jinja 标记是字符串格式,我如何在 django 和 jinja2 中使用它?

python - Jinja2 模板宏中的 NamedTuples

python - 如何在Python中更改数据框枢轴的布局

python - 在 python 中隐藏 chromeDriver 控制台