Last active
December 28, 2015 03:29
-
-
Save joaodubas/7435932 to your computer and use it in GitHub Desktop.
Dynamic Django Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
from django import forms | |
from collections import OrderedDict | |
def form_factory_for_fields(name, fieldnames, fields=None): | |
"""form_factory_for_fields -- Create dynamically a form class containing a | |
list of set fields. | |
name -- name for the Form class | |
fieldnames -- a list of field names | |
fields -- a list of form fields, optional. | |
Usage: | |
>>> name = 'DynamicForm' | |
>>> fields = ['name', 'password', 'address'] | |
>>> DynamicForm = form_factory_for_fields(name, fields) | |
""" | |
fields = fields or [forms.CharField() for i in xrange(len(fieldnames))] | |
return type( | |
name, | |
(forms.Form, ), | |
OrderedDict(zip(fieldnames, fields)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment