I want to create a form with fields for each of the last 10 years. So for 2020-2011 I want, say, an IntegerField for each year with the variable names year_2020, year_2019, year_ 2018, ... It'd also be nice if they had the appropriate labels too, i.e. 2020, 2019...
I could do this by writing something out for each year individually but I thought it'd be nicer and more efficient (?) to generate them using a for loop. Is this possible?
I saw this question about generating fields in the template using a for loop but I'm wondering how to generate fields in the python form class itself (not sure what to call it; please excuse my ignorance). I've seen this question but I can't seem to get it to work. I'm also not fond of that solution since it doesn't give the fields descriptive names like year_2020.
This is my code so far; apologies for any errors.
The python:
forms.py
class YearForm(FlaskForm):
year = IntegerField(validators=[NumberRange(min=0,max=100000,message='Please enter an integer above 0.'),
InputRequired(message='Please enter a value.')])
class RentForm(FlaskForm):
years = FieldList(FormField(YearForm), min_entries=10)
The template:
form.html
for year in rentForm.years:
<p>{{ year.label }}: {{ year(size=32) }}
{% for error in year.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
It looks like I'm accessing the fields incorrectly in the template. What is the correct way? And how can I give the fields more descriptive labels and variable names?
Any help would be greatly appreciated; thanks!
EDIT: if this could be more easily done in another language please let me know. I just started learning Flask/Python and am not married to either.