所以我使用wtforms来生成无线电字段,但我需要它们是动态的,就像有12个问题,每个问题都会获得一组无线电字段。我尝试过FormField,它给了我想要的东西,但所有问题的名称都相同,有没有更好的方法呢?
输出应该是这样的:
Question
Radiofield1 radioField1
Question
Radiofield2 radioField2
修改: 我继续完成HTML字段,但它会非常有用。 我不记得我做了什么,但这很接近它我可以渲染字段但id不会改变我尝试将元组传递给
选项但它为每个问题呈现动态广播字段,而不是为每个问题呈现1套
Forms.py
class QuestionRadio(FlaskForm):
rad=RadioField("rad",choices=[(1,'Yes'),(2,'No')],id="opt")
class QuestionForm(FlaskForm):
options=FieldList(FormField(QuestionRadio),min_entries=1)
Views.py
#This is the question list
question=[(ques.id,ques.question) for ques in Questions.query.all()]
form=QuestionForm()
#I don't remember what I did after this
template.html
{% for key,val in question %}
<h4>key. val</h4>
{{form.options}}
{% endfor%}
答案 0 :(得分:0)
wforms documentation建议创建一个虚拟类并在视图中动态添加字段。
这是文档中的示例:
def my_view():
class F(MyBaseForm):
pass
F.username = StringField('username')
for name in iterate_some_model_dynamically():
setattr(F, name, StringField(name.title()))
form = F(request.POST, ...)
# do view stuff
在您的情况下,代码可能看起来像这样(未经测试):
def my_view():
class QuestionForm(Form):
pass
for q in Questions.query.all():
field = RadioField(q.question,choices=[(1,'Yes'),(2,'No')],id=q.id)
setattr(QuestionForm, q.id, field)
form = QuestionForm(request.POST, ...)
# do view stuff