且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用WTForms表单数据更新模型

更新时间:2023-02-15 14:27:33

使用表单的

Use the form's populate_obj method to fill in the model. It sets an attribute of the same name as each field.

form.populate_obj(car)
db.session.commit()

如果简单的按字段名称设置属性"行为不适用于给定的模型/表单对(尽管在您的情况下应该如此),则可以覆盖该方法.

If the simple "set attribute by field name" behavior isn't appropriate for a given model/form pair (although it should be in your case), you can override the method.

class SpecialCarForm(FlaskForm):
    ...

    def populate_obj(obj):
        # mess with data, set extra fields, etc.
        # potentially call super after
        super().populate_obj(obj)