Reputation: 2413
I have a form setup like so:
class AddressForm(FlaskForm):
line1 = StringField()
city = StringField()
postcode = StringField()
class PlaceForm(FlaskForm):
name = StringField()
address = FormField(AddressForm)
And then I have a Flask view something like this:
@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)
The api.get_place(ident)
returns data that doesn't match the shape of the field names in my Form
classes, so my forms are always empty when rendered in the browser. For example, the response from the API might look like this:
{
"place": {
"place_name": "Foobar",
"address": {
"address1": "500 5th St",
"locality": "San Francisco",
"post_code": "90210"
}
}
}
How do I customize the code populates the PlaceForm
with data when passing in obj
?
Upvotes: 0
Views: 338
Reputation: 4767
I can't quite tell if this is actually the pattern you want. Since edit_place
has both GET and POST methods do you really want to populate the form in both cases from the api.get_place()
function, possibly overwriting the data from the request?
Anyway you might try something like the following:
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
Upvotes: 0