0
votes

I am creating my wtforms dynamically from my database.

def create_form_field_class(fields):
   form_fields = {}
   for i in fields:
       field_id = i.name
       form_fields[field_id] = TextField(label=i.label, validators=[Optional()])
   return type('Form', (Form,), form_fields)

Currently, all field types are "TextField". Since I also have the field type stored in my database (BooleanField, TextAreaField, etc..), I would also like to set this dynamically.

form_fields[field_id] = ???i.type???(label=i.label, validators=[Optional()])

There must be a quick way to do this.

1

1 Answers

0
votes

Okay, the way I solved this was.

import wtforms

def create_form_field_class(fields):
   form_fields = {}
   for i in fields:
       field_id = i.name
       form_fields[field_id] = getattr(wtforms, str(i.type))(label=i.label, validators=[Optional()])
   return type('Form', (Form,), form_fields)

I wonder if there are better methods out there.