April 6th, 2008 @ 22:03
Building dynamic forms with Django newforms module is quite undocumented, though it’s quite easy to do. All you need to do is to hook up the __init__ function of the form, raise the __init__ to the parent forms.Form class and then add your dynamically generated fields to self.fields dict.
Here is a quick snippet demonstrating it, which will create a form with n integer fields named from 0 to (n – 1), but you will easily be able to heavily extend it.
from django import newforms as forms class MyForm (forms.Form): def __init__ (self, n, *args, **kwargs): forms.Form.__init__ (self, *args, **kwargs) for i in range (0, n): field = forms.IntegerField (label = "%d" % i, required = True, min_value = 0, max_value = 200) self.fields["%d" % i] = field
April 7th, 2008 at 2:01 am
Cool. I haven’t used tried newforms yet, looks interesting.
April 11th, 2008 at 7:12 am
Hey, that is very handy. I now also use this to initialise the forms initial values:
def __init__(self, referenceModelInstance, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.referenceModelInstance = referenceModelInstance for field in self.fields self.fields[field].initial = getattr(self.referenceModelInstance,field)When creating the form I feed it the model for which I want the form to be instantiated. This of course requires the fields to have the same name as the model fields.
Are there any other drawbacks that I am not thinking about with this code?
April 11th, 2008 at 10:06 am
Looks pretty good to me
July 13th, 2008 at 3:55 pm
@Roderik: have you tried using a ModelForm?
July 23rd, 2008 at 7:31 pm
Awesome. Thank you.
October 20th, 2008 at 11:04 pm
Thanks, this is exactly what I was looking to do. I was worried it wouldn’t be possible. How did you discover this?
June 16th, 2009 at 8:01 am
Trial of dynamic forms looks pretty good and interesting to me.
February 13th, 2010 at 4:29 am
[...] iXce’s blog » Blog Archive » Tip of the day: Dynamic forms with Django newformsHow to customize your Django forms at instantiation time i.e., control what fields your form has and how they look at run time. [...]