Skip to content
Advertisement

How can I create a form from a list of models using WTForms?

I have a list of Prediction models. I want to bind them to a form and allow the use to post back. How can I structure my form so the post associates a Home/Away score with a Prediction model’s id field for each item I bind to the form?

view

JavaScript

form

JavaScript

template

JavaScript

I am unable to get my data to bind correctly on POST. The required validators continually fail because the post data is missing all the Required fields.

Advertisement

Answer

You need a subform that will bind to the items in a list of predictions:

The form you have described will only allow you to submit a single prediction. There seems to be a discrepancy because you bind an iterable of predictions and it would appear that you want a home and away prediction for each. In fact as it stands it will never post back an id field. This will always cause you to fail form validation. I think what you want is a list of subforms. Like so:

JavaScript

Your view will need to return something along the lines of:

JavaScript

Your form will need to change to something more like this:

JavaScript

Now this will print a <ul> with an <li> per item because thats what FieldList does. I’ll leave it up to you to style it and get it into a tabular form. It might be a bit tricky but its not impossible.

On POST a you will get a formdata dictionary with a home and away score for each prediction’s id. You can then bind these predictions back into your SQLAlchemy model.

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