如何遍历wtform RadioField列表?我尝试通过以下代码实现这一目标:
下面是我的.py文件中的代码。生成字段的代码在 init 方法中。
ionViewWillEnter(){
firebase.database().ref('/posts/').once('value').then(snapshot => {
snapshot.forEach(childSnapshot => {
//rest of the code
});
});
尝试执行此操作时,出现以下错误:
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)
答案 0 :(得分:1)
WTForms基于python的元编程类,默认情况下,一切正常运行,期望您在一定时间内采取某些措施。为了使字段起作用,应该将它们绑定(通常绑定到表单),并且WTForm在meta-class DefaultMeta期间通过特殊的form init绑定字段。但是WTForms需要知道要绑定的字段以及这些字段存储在_unbound_fields list中。因此,在您的情况下,为避免元编程的麻烦,一个简单的解决方案是将您新创建的字段