WTForms create variable number of fields

僤鯓⒐⒋嵵緔 提交于 2019-12-03 02:22:06

It was in the docs all along.

def my_view():
    class F(MyBaseForm):
        pass

    F.username = TextField('username')
    for name in iterate_some_model_dynamically():
        setattr(F, name, TextField(name.title()))

    form = F(request.POST, ...)
    # do view stuff

What I didn't realize is that the class attributes must be set before any instantiation occurs. The clarity comes from this bitbucket comment:

This is not a bug, it is by design. There are a lot of problems with adding fields to instantiated forms - For example, data comes in through the Form constructor.

If you reread the thread you link, you'll notice you need to derive the class, add fields to that, and then instantiate the new class. Typically you'll do this inside your view handler.

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!