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