【发布时间】:2014-04-23 15:02:26
【问题描述】:
我目前正在尝试使用WTForms 的FieldList 和FormField 附件来允许用户添加具有相应覆盖量的自定义位置子集。
表单向用户提供一些标准输入,然后使用一组字段 (FormField) 进行初始化,每个字段都有一个位置选择输入和一个覆盖范围输入。
Javascript 允许用户根据需要添加或删除额外的位置覆盖字段集,以反映准确的文档信息。
问题: 作为一种解决方法,我一直在通过在表单处理程序的 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,我将不胜感激。
【问题讨论】:
标签: python google-app-engine jinja2 app-engine-ndb wtforms