简体   繁体   中英

Populating WTForm FormField in a Flask view when object doesn't match form field names

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM