Reputation: 1213
I'm working on function (in Django 1.4, python 2.7.2+) that generates the Form for specified Model and returns it. I've got trouble using type() method with 3 arguments, because I want to specify Form's inner Meta class. Django documentation gives an example of auto-generated Form for Model:
class PartialAuthorForm
m(ModelForm):
class Meta:
model = Author
Now I want to generalize it and make forms automatically. So I want to specify Meta inside returned Form, and attribute "model = model_cls" in it.
from django.forms import ModelForm
def generate_form_for(model_cls):
ret_cls = type(model_cls.__name__ + "Form", (ModelForm,), {???})
I don't know what "???" should be replaced with. Do you?
Upvotes: 2
Views: 637
Reputation: 6323
Check how Django modelform_factory
works:
https://github.com/django/django/blob/master/django/forms/models.py#L372
Meta
is class attribute.
Upvotes: 0
Reputation: 10676
I've solved this by doing something like this:
Meta = type('Meta', (), {
'model': ExampleModel,
})
ExampleForm = type('ExampleForm', (), {
'Meta': Meta,
})
Upvotes: 2