ash ash - 1 year ago 140
Python Question

WTForms create variable number of fields

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

from wtforms import Form, RadioField
from wtforms.validators import Required

class VariableForm(Form):

def __init__(formdata=None, obj=None, prefix='', **kwargs):
super(VariableForm, self).__init__(formdata, obj, prefix, **kwargs)
questions = kwargs['questions']
// How to to dynamically create three questions formatted as below?

question = RadioField(
# question ?,
choices = [('yes', 'Yes'), ('no', 'No')],

questions = ("Do you like peas?", "Do you like tea?", "Are you nice?")
form = VariableForm(questions = questions)

ash ash
Answer Source

It was in the docs all along.

def my_view():
    class F(MyBaseForm):

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download