WTForms: FieldList from FormField cannot load embedded data
I have a custom field inside FormField inside 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 submitted, is saved to the object as follows:
document = {
'title': unicode,
'description': unicode,
'manager': unicode,
'locations': [{
'id': uuid.UUID,
'title': unicode,
'location': {'coordinates':[float], 'text':unicode}
}],
}
When I try to load data into a form for a GET handler, everything but the locations are loaded ok:
f = form(MultiDict(document))
f.locations.data
>> {'id':'','title':'','location':''}
I did some debugging and found that WTForms, when loading document data into a form, looks for "location-0-location", but MultiDict (), but those keys don't exist. MultiDict does not convert the list of dictionaries to the key "location-i -...".
What's the correct way to create a WTForm for such a nested data structure?
+3
source to share
2 answers
I had the same problem and was able to sort it by flattening the list down to a dict with the prefix added.
Something like:
document = {
'title': unicode,
'description': unicode,
'manager': unicode,
}
locations = [{
'id': uuid.UUID,
'title': unicode,
'location': {'coordinates':[float], 'text':unicode}
}]
document.update({'locations-%s-%s' % (num, key): val for num, l in enumerate(locations) for key, val in l.items()})
+1
source to share
with WTFORMS 2.1
data:
document = {
'title': unicode,
'description': unicode,
'manager': unicode,
'locations': [{
'id': uuid.UUID,
'title': unicode,
'location': {'coordinates':[float], 'text':unicode}
}],
}
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)
try this:
f = ProjectForm() f.process(data=document) f.locations.data
0
source to share