WTForms create variable number of fields

前端 未结 3 641
执笔经年
执笔经年 2021-02-05 17:18

How I would dynamically create a few form fields with different questions, but the same answers?

from wtforms import Form, RadioField
from wtforms.validators imp         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 17:19

    You're almost there:

    CHOICES = [('yes', 'Yes'), ('no', 'No')]
    
    class VariableForm(Form):
    
        def __new__(cls, questions, **kwargs):
            for index, question in enumerate(questions):
                field_name = "question_{}".format(index)
                field = RadioField(question,
                                      validators=[Required()],
                                      choices=CHOICES)
                setattr(cls, field_name, field)
            return super(VariableForm, cls).__new__(cls, **kwargs)
    

提交回复
热议问题