![](/img/trans.png)
[英]What WTForm field do you use in flask when you want to enter a list/tuple into a form?
[英]Populating WTForm FormField in a Flask view when object doesn't match form field names
我有这样的表单设置:
class AddressForm(FlaskForm):
line1 = StringField()
city = StringField()
postcode = StringField()
class PlaceForm(FlaskForm):
name = StringField()
address = FormField(AddressForm)
然后我有一个Flask视图,像这样:
@bp.route("/places/<ident>", methods=['GET', 'POST'])
def edit_place(ident):
place = api.get_place(ident)
form = PlaceForm(obj=place)
if form.validate_on_submit():
# do stuff with the form data
return render_template('place/edit.html', form=form)
api.get_place(ident)
返回的数据与我的Form
类中的字段名称的形状不匹配,因此在浏览器中呈现时,我的表单始终为空。 例如,来自API的响应可能如下所示:
{
"place": {
"place_name": "Foobar",
"address": {
"address1": "500 5th St",
"locality": "San Francisco",
"post_code": "90210"
}
}
}
当传入obj
时,如何自定义代码以数据填充PlaceForm
?
我不太清楚这是否真的是您想要的模式。 由于edit_place
具有GET和POST方法,您是否真的想在两种情况下都通过api.get_place()
函数填充表单,可能会覆盖请求中的数据?
无论如何,您可以尝试以下操作:
class PlaceForm(FlaskForm):
name = StringField()
address = FormField(AddressForm)
def __init__(self, *kwargs):
super().__init__()
self.address, self.name = # some code to populate with data from kwargs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.