我想制作具有多种选择的考试表格。 如何避免在表单类中手动编写radioField,radioField重复 N 次
views.py
@app.route("/exams", methods=['GET', 'POST'])
def exams():
radios = []
if request.method == 'POST':
#exam_answers_form = forms.(request.form)
class NForm(forms.ExamAnswersForm):
pass
n = NForm()
datos = Questions.query.add_columns('question').filter_by(modules_id=5).all()
for name in datos:
setattr(n, 'question', RadioField(name, choices=[('value','descriptions'),('value_two','whatever')]))
n.question.append()
x = n
return render_template('exams/exams_answers.html', form=x )
return render_template('exams/exams.html')
forms.py
class ExamAnswersForm(Form):
question = RadioField(choices=[()])
答案 0 :(得分:0)
您可以编写这样的动态表单,假设您知道如何查询数据库以某种格式返回数据,则可以调整以下代码以使其适合您:
class ExamAnswersForm(Form):
# get static data from database
data = {'q_1': ('Is FEAR a good book?', (1, 'Yes'), (0, 'No')),
'q_2': ('Is the Earth flat?', (0, 'Yes'), (1, 'No'))}
for label in data.keys():
vars()[label] = RadioField(data[label][0], choices=[data[label][1], data[label][2]])
如果要使其更具动态性,可以创建一个返回初始化形式的方法:
def exam_answers_form(*args, **kwargs):
# do something with *args and **kwargs to get dynamic data from database
data = {'q_1': ('Is FEAR a good book?', (1, 'Yes'), (0, 'No')),
'q_2': ('Is the Earth flat?', (0, 'Yes'), (1, 'No'))}
class ExamAnswersForm(Form):
pass
for label in data.keys():
setattr(ExamAnswersForm, label, RadioField(data[label][0], choices=[data[label][1], data[label][2]]))
return ExamAnswersForm()