开发者

building dynamic forms in django

I'm trying to build a form dynamically based on the field and its defin开发者_Go百科itions 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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜