On Sat, Feb 7, 2009 at 12:52 PM, Jim Jones <jjimjjo
...@googlemail.com> wrote:
> is there a way to dynamically assemble a form at runtime?
This is possible by creating a subclass of Form inside your view function:
def edit(request):
class F(Form):
pass
F.username = TextField('username')
for name in iterate_some_model_dynamically():
setattr(F, name, TextField(name.title()))
form = F(request.POST, obj=mymodel)
# do view stuff
Note that we create a Form subclass inside the view function, thus if the
form can change between requests, you won't get an issue with conflicting
attributes and thread-safety. If the form can be generated once at
application startup, then you can simply move your form creation to module
level, or use a factory type approach (see model_form in wtforms.ext.django
for inspiration there.) For example:
def my_form_factory(model):
F = type(type(model).__name__ + 'Form', (Form, ), {})
for name in dir(model):
field = getattr(model, name)
if type(field).__name__ == 'CharField':
setattr(F, name, TextField(field.label))
UserForm = my_form_factory(models.User)
The reason we don't support adding fields directly on to form _instances_,
only onto form classes is that we pass the input data to the form at
instantiation time. This means that at instantiation time the form needs to
know all its fields. It also semi-implies the contract where the form is
bound to one set of data per instantiation.
It should be noted that since forms can subclass other forms, you can mix
together dynamic forms and 'hardcoded' forms in any order you wish:
class CsrfForm(Form):
csrf_token = HiddenField()
class UserForm(CsrfForm):
pass
for x in dir(User):
setattr(UserForm, x, TextField(x))
class UserProfileForm(UserForm):
bio = TextAreaField("User Biography")
There's a lot of possibilities here, depending on what you need to do. If
you are designing automagic CRUD forms for some ORM framework other than
django, let us know, we might be interested in co-opting it as an extension.
We already have planned for 0.4 a SQLAlchemy form factory similar to the
django version as well. Hope I was of some help.
James