Search code examples
python-3.xflaskjinja2flask-wtforms

How to Loop Through RadioField List


How can I loop through a list of wtform RadioFields? I attempted to achieve this with the following code:

Below is my code in my .py file. The code that generates the fields is in the init mehtod.

from flask import (Flask, render_template, request,
                session, url_for, redirect)
from flask_wtf import FlaskForm
from wtforms import SubmitField, RadioField, StringField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'my_secret'

class AssessmentForm(FlaskForm):
    """Questionnaire Assessment Form"""

    submit = SubmitField('Submit')

    def __init__(self):
        super().__init__()

        #Get Activity Questions
        f = open(r'my_path\questions.txt','r')
        q = f.readlines()
        q = [s.strip() for s in q]
        f.close()
        self.questions = q

        #Create 60 rows of 5 radio buttons
        self.radio_row = []
        for i in range(60):
            #row of 5 radio fields
            rr = RadioField(label=f'row{i+1}',choices=[('s_dis', 'Strongly Dislike'), 
                                    ('dis', 'Dislike'),
                                    ('unsure', 'Unsure'),
                                    ('dis', 'Like'),
                                    ('s_like', 'Disagree')])
            self.radio_row.append(rr)

@app.route('/', methods=['GET','POST'])
def assessment():
    form = AssessmentForm()

    if form.validate_on_submit():
        return redirect(url_for('results'))

    return render_template('questionnaire.html', form=form)

@app.route('/results')
def results():
    return render_template('results.html')

if __name__ == "__main__":
    app.run(debug=True)

When I try to attempt this, I get the following error:

 TypeError: 'UnboundField' object is not iterable

Solution

  • WTForms are based on python's classes meta-programming and to everything work correctly by default expects from you a certain actions in a certain time. For fields to work they should be bound (to a form, usually), and WTForms binds fields through special meta-class DefaultMeta during form init. But WTForms needs to know what fields to bind and those field are stored in _unbound_fields list. So in your case, to avoid complications of meta-programming, a simple solution would be is to append your newly created fields to _unbound_fields before super().__init__() call, so WTForms will bind it for you during init process.

    P.S. Also, recipes from here might be useful too.