Issue
So I'm using wtforms to generate radio fields but I need them to be dynamic like if there are 12 questions each question would get a set of radio fields. I tried FormField which gave me what i wanted but the names are same for all the questions is there a better way to do this?
the output should be like this:
Question
Radiofield1 radioField1
Question
Radiofield2 radioField2
Edit: I moved on to complete HTML fields but it would be really helpful. I don't remember much as to what I did but this was close to it I could render the fields but the id wouldn't change I tried passing the tuples to
options but it rendered dynamic radio fields for each question rather than 1 set for each question
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%}
Solution
The wforms documentation suggests creating a dummy class and dynamically adding fields in your view.
This is the example from the 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
In your case the code might look something like this (untested):
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
Answered By - snakecharmerb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.