Skip to main content
 首页 » 编程设计

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

2025年05月04日15三少

我目前正在尝试使用 WTForms 的 FieldList 和 FormField 附件来允许用户添加具有相应覆盖范围的自定义位置子集数额。

该表单向用户提供一些标准输入,然后使用一组字段 (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] 

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