Forums

Flask form defined programatically

I'm trying to define a wtf Form programatically, ie, not typing things out by hand. I want to avoid ABCForm, and use ABCForm2 instead (the list of variables could eventually be passed in):

class ABCForm(Form):
    a = FloatField('a')
    b = FloatField('b')
    c = FloatField('c')

class ABCForm2(Form):
    def __new__(cls, *args, **kwargs):
        fieldnames =  ['a','b','c']
        for fieldname in fieldnames:
            field = FloatField(fieldname)
            setattr(cls, fieldname, field)
        return super(ABCForm2, cls).__new__(cls, *args, **kwargs)

However, I'm having trouble calling form = ABCForm2(csrf_enabled=False) in my flask_app. The error I get is

File "/home/FPFIconsulting/mysite/growth_flask/flask_app.py", line 37, in test2
    form = ABCForm2(csrf_enabled=False)
  File "/usr/local/lib/python2.7/dist-packages/wtforms/form.py", line 178, in __call__
    return type.__call__(cls, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/flask_wtf/form.py", line 77, in __init__
    super(Form, self).__init__(formdata, obj, prefix, csrf_context=csrf_context, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/wtforms/ext/csrf/form.py", line 21, in __init__
    super(SecureForm, self).__init__(formdata, obj, prefix, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/wtforms/form.py", line 226, in __init__
    super(Form, self).__init__(self._unbound_fields, prefix=prefix)
  File "/usr/local/lib/python2.7/dist-packages/wtforms/form.py", line 38, in __init__
    for name, unbound_field in fields:
TypeError: 'NoneType' object is not iterable

What am I doing wrong?

Hmm, I can't see anything obviously wrong -- but I'm not a WTForms expert. Perhaps it's worth posting this one on Stack Overflow, if you haven't already?