Update model with WTForms form data

gec*_*kos 1 python flask wtforms flask-sqlalchemy flask-wtforms

I have some Flask-SQLAlchemy models and Flask-WTF forms generated with wtforms_alchemy to represent them. I implemented a method on each model to update its attributes from a form's data. For each new model and field I have to update these methods, which is annoying. Is there a way to make this more automatic, or a a feature in the libraries I'm using that I'm missing?

def edit_car(car_id):
    form = CarForm(request.form)
    if form.is_valid():
        car = Car.query.get_or_404(car_id)
        car.from_form(form) # Update car fields
        ...
        # save car in database ...

class Car(db.Model):
   color = db.Column(db.String(10)) 
   ...

   def from_form(self, form):
        self.color = form.color.data
        ... # all other fields
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 5

使用表单的populate_obj方法填写模型。它设置与每个字段同名的属性。

form.populate_obj(car)
db.session.commit()
Run Code Online (Sandbox Code Playgroud)

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

class SpecialCarForm(FlaskForm):
    ...

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