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:
我正在处理函数(在Django 1.4,python 2.7.2+中),它为指定的Model生成Form并返回它。我在使用带有3个参数的type()方法时遇到了麻烦,因为我想指定Form的内部Meta类。 Django文档给出了一个自动生成的Form模型示例:
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.
现在我想概括它并自动创建表单。所以我想在返回的Form中指定Meta,并在其中输入属性“model = model_cls”。
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?
我不知道“???”应该换成。你做?
2 个解决方案
#1
1
I've solved this by doing something like this:
我通过做这样的事情解决了这个问题:
Meta = type('Meta', (), {
'model': ExampleModel,
})
ExampleForm = type('ExampleForm', (), {
'Meta': Meta,
})
#2
0
Check how Django modelform_factory
works:
检查Django modelform_factory的工作原理:
https://github.com/django/django/blob/master/django/forms/models.py#L372
Meta
is class attribute.
Meta是类属性。
#1
1
I've solved this by doing something like this:
我通过做这样的事情解决了这个问题:
Meta = type('Meta', (), {
'model': ExampleModel,
})
ExampleForm = type('ExampleForm', (), {
'Meta': Meta,
})
#2
0
Check how Django modelform_factory
works:
检查Django modelform_factory的工作原理:
https://github.com/django/django/blob/master/django/forms/models.py#L372
Meta
is class attribute.
Meta是类属性。