Update model with WTForms form data

本秂侑毒 提交于 2019-12-11 08:27:17

问题


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

回答1:


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)


来源:https://stackoverflow.com/questions/46609908/update-model-with-wtforms-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!