dynamic forms in dajngo

Март 18, 2010

Django has a very convenient forms framework and I want to show how to implement a form with dynamic set of fields.
First — declare a form class:

from django import forms

class SomeAddressForm(forms.Form):

Then the tricky part — declare a function that returns type of dynamic form:

def getAddressForm(addMoreField):	
	fields = {"city" : forms.ModelChoiceField(queryset=City.objects, label=strings.city, empty_label=strings.notDefined),
		"address" : forms.CharField(label=strings.address),
		"phone" : forms.CharField(label=strings.phone),
		"email" : forms.EmailField(label=strings.email),
	if addMoreField:
		fields["someBoolField"] = forms.BooleanField(required=False, label=strings.boolLabel)
        return type('SomeAddressForm', (forms.BaseForm,), { 'base_fields': fields })

So, there is a static field set in the variable fields and some additional fields could be added if some condition happens (here a bool variable addMoreField is true).
Now in a view function call getAddressForm(true)() — to create a form with additional fields and getAddressForm(true)(data) — to create a bound form.

posted in Python by dmitko

Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org