6

Django's form library has a feature of form sets that allow you to process dynamically added forms. For example you would use form sets if your application has a list of bookmarks you could use form sets to process multiple forms that each represent a bookmark.

What about if you want to dynamically add a field to a form? An example would be a survey creation page where you can dynamically add an unlimited number of questions. How do you handle this in Django?

hekevintran
  • 22,822
  • 32
  • 111
  • 180

3 Answers3

7

Look at this recent post by Jacob Kaplan-Moss, one of the original founders of Django: "Dynamic form generation". It uses an example to show you the process step by step. Great read.

There is also a 2008 article by James Bennett, Django's release manager.

Ludwik Trammer
  • 24,602
  • 6
  • 66
  • 90
5

To add, remove and change fields on a Form or ModelForm, just override __init__() like this:

class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
    user = kwargs.pop('user')
    other_stuff = kwargs.pop('stuff')

    super(MyForm, self).__init__(*args, **kwargs)

    self.fields['my_dynamic_field'] = forms.Field(...)

    # Add fields based on user or other_stuff

And use it like this: form = MyForm(user = user, stuff = stuff)

garcianavalon
  • 745
  • 6
  • 12
knutin
  • 5,033
  • 19
  • 26
5

In python you can instantiate a class dynamically. knutin shows a good example of dynamically customizing a form based, and adding a few fields.

You may also create the whole form dynamically, as taken from the example given by James Bennett:

def make_contact_form(user):
    fields = { 'name': forms.CharField(max_length=50),
           'email': forms.EmailField(),
           'message': forms.CharField(widget=forms.Textarea) }
    if not user.is_authenticated():
    fields['captcha'] = CaptchaField()
    return type('ContactForm', (forms.BaseForm,), { 'base_fields': fields })
lprsd
  • 84,407
  • 47
  • 135
  • 168