当对象与表单字段名称不匹配时,在Flask视图中填充WTForm FormField

时间:2018-11-20 00:31:14

标签: python flask flask-wtforms wtforms

我的表单设置如下:

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"
    }
  }
}

在传递PlaceForm时如何自定义代码以数据填充obj

1 个答案:

答案 0 :(得分:0)

我不太清楚这是否真的是您想要的模式。由于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