Skip to content
Advertisement

How to collect WTForms data through loop without explicitly stating the name of each field?

I am following CoreyMSchafer’s Flask-blog tutorial. Here, I can create, update and delete posts using WTForms and SQLAlchemy. However, to do that, I have to explicitly mention the name of the form fields. For example, to update a post (assuming a post only has title and content):

JavaScript

where the model is

JavaScript

and the WTForm is

JavaScript

However, what if my form has hundreds of fields (such as a star which has hundreds of parameters and let’s say we want a post to store all these parameters for a star)!? Do I have to explicitly mention them in models, routes, forms – everywhere? or is it possible to create the model/form with all the fields and then somehow loop through the fields to avoid typing each of them in routes?

Advertisement

Answer

form.data returns all of the form fields and its values in dict object where dict keys is field name.

But: you may use form.populate_obj(post) method for update an object (field names in form and model must be equal)

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement