views:

194

answers:

2

I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label.

How do I build a form dynamically in my view from the data in the db?

Thanks

+2  A: 

Django does a great job auto-generating forms from your model definitions.

The first step might be to create a Django model that mirrors your existing database.

Regarding the checkbox/textfield stuff:

Django has a great separation between fields and widgets. You may have a IntegerField that stores numbers, but you can vary the widget that is displayed to the user when they want to edit that number. In some cases you might have an input box, in others a textarea, or perhaps a dropdown. The field will take care of details such as type conversion and validation, the widget determines what the form field looks like.

Certain field types have default widgets associated with them, but you can override them.

Also, note that there is a difference between form fields and model fields.


To do it dynamically, can add items to the self.fields SortedDict on the fly. I.E:

from django.forms.forms import Form
from django.forms.fields import CharField
class FunkyForm(Form):
    def __init__(self, *args, **kwargs):
        super(FunkyForm, self).__init__(*args, **kwargs)
        for item in range(5):
            self.fields['test_field_%s' % item] = CharField(max_length=255)

Will give a you a form class that instantiates with 5 dynamically generated CharFields.

Koobz
the project is model free. There are no models defined. Let's assume that the data is being read from an input file like XML instead of a database.
+2  A: 

Here are the slides from a talk I gave at EuroDjangoCon about doing precisely this: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth

Alex Gaynor
Good stuff! Wish I had read this when I started out because a lot of what you're showing here teases your brain when you get into actually using Django forms.
Koobz