WTForms:FormField的FieldList无法加载嵌套数据 [英] WTForms: FieldList of FormField can't load nested data
问题描述
我在FieldList内的FormField内有一个自定义字段:位置
I have a custom field inside a FormField inside a FieldList: locations
class LocationForm(Form):
id = HiddenField('id')
title = StringField(_l('Title'), [Required()])
location = CoordinatesField(_l('Coordinates'))
class ProjectForm(Form):
title = StringField(_l('Title'))
manager = StringField(_l('Manager'))
description = StringField(_l('Description'))
locations = FieldList(FormField(LocationForm), min_entries=1)
提交时,此表单将保存到这样的对象中:
This form when submited is saved to an object like this:
document = {
'title': unicode,
'description': unicode,
'manager': unicode,
'locations': [{
'id': uuid.UUID,
'title': unicode,
'location': {'coordinates':[float], 'text':unicode}
}],
}
当我尝试将数据加载到GET处理程序的表单中时,一切但位置都很好:
When I try to load the data in to the form for a GET handler, everything but the locations loads fine:
f = form(MultiDict(document))
f.locations.data
>> {'id':'','title':'','location':''}
我进行了一些调试,发现WTForms在将文档数据加载到表单中时搜索了"locations-0-location",但是搜索了MultiDict()但该键不存在.MultiDict不会将字典列表转换为键"locations-i -...".
I did some debugging and found that WTForms while loading the document's data in to the form searches for 'locations-0-location' but MultiDict() but that keys doesn't exists. MultiDict doesn't convert a list of dictionaries to the key 'locations-i-...'.
为这样的嵌套数据结构制作WTForm的正确方法是什么?
What is the right way to make a WTForm for such a nested data structure?
推荐答案
数据:
document = {
'title': unicode,
'description': unicode,
'manager': unicode,
'locations': [{
'id': uuid.UUID,
'title': unicode,
'location': {'coordinates':[float], 'text':unicode}
}],
}
您使用WTFORMS设置数据结构:
you set the data structure with WTFORMS:
class LocationForm(Form):
id = HiddenField('id')
title = StringField(_l('Title'), [Required()])
location = CoordinatesField(_l('Coordinates'))
class ProjectForm(Form):
title = StringField(_l('Title'))
manager = StringField(_l('Manager'))
description = StringField(_l('Description'))
locations = FieldList(FormField(LocationForm), min_entries=1)
尝试一下:
f = ProjectForm()
f.process(data=document)
f.locations.data
这篇关于WTForms:FormField的FieldList无法加载嵌套数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!