我有FieldList(FormField(SubForm))
的设置,其中SubForm
包含SelectField
,其选择在运行时确定(在视图函数中)。目前我有以下设置,它基本上为SubForm
派生了一个新类,每次调用时都有选择:
from flask import Flask, render_template_string, url_for
from wtforms import SelectField, StringField, FieldList, FormField
from flask_wtf import FlaskForm as Form
app = Flask(__name__)
app.secret_key = 'secret_key'
class BaseForm(Form):
@classmethod
def append_field(cls, name, field):
setattr(cls, name, field)
return cls
class SubForm(BaseForm):
title = StringField('SubForm')
class RootForm(BaseForm):
entries = FieldList(FormField(SubForm))
@app.route('/test/', methods=['GET', 'POST'])
def form_viewer():
form = RootForm(title='Title')
subformclass = SubForm
subformclass = subformclass.append_field('options',
SelectField('Options', choices=[('%i' %i,'option%i' %i) for i in range(1,5)]))
if form.validate_on_submit():
while form.entries:
subform = form.entries.pop_entry()
print(subform.options.data)
else:
print(form.errors)
for entry in range(1,3):
subform = subformclass()
subform.title = 'SubTitle%i' %entry
form.entries.append_entry(subform)
html_template = '''<html>
<form action="{{ url_for('form_viewer') }}" method=post>
{{ form.hidden_tag() }}
{{ form.entries() }}
<input type=submit value=Submit>
</form>
</html>'''
return render_template_string(html_template, form=form)
现在我的问题是,如果应用程序在GET和POST请求之间重新启动(因为事情发生),那么在尝试访问提交的表单数据时它会引发AttributeError: 'UnboundField' object has no attribute 'data'
。
如何解决这个问题?或者是否有另一种更好的方法来获得具有可变选择的可变数量的SelectField
?
修改
我认为问题是,在FieldList
创建后,我更改了SubForm
。所以现在我以类似的方式创建FieldList
比如SelectField
:
formclass = RootForm.append_field('entries', FieldList(FormField(subformclass)))
但我仍然想知道这是否是我应该这样做的方式?感觉就像是,可能会有更优雅的解决方案。