Skip to content

Instantly share code, notes, and snippets.

@joaodubas
Last active December 28, 2015 03:29
Show Gist options
  • Save joaodubas/7435932 to your computer and use it in GitHub Desktop.
Save joaodubas/7435932 to your computer and use it in GitHub Desktop.
Dynamic Django Form
# 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