views:

318

answers:

3

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?

+1  A: 

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):
    super(MyForm, self).__init__(*args, **kwargs)

    user = kwargs.pop('user')
    other_stuff = kwargs.pop('stuff')

    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)

knutin
+1  A: 

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 })
Lakshman Prasad
+1  A: 

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