Andy McKay

Mar 24, 2010

Creating a ModelForm dynamically


A simple short snippet for creating a ModelForm for an object dynamically. This is a useful library function to validate data and save changes to a model without having to declare a form:

from django import forms

def model_to_modelform(model):
    meta = type('Meta', (), { "model":model, })
    modelform_class = type('modelform', (forms.ModelForm,), {"Meta": meta})
    return modelform_class

Based on "So you want a dynamic form".