【发布时间】:2010-11-18 02:06:47
【问题描述】:
我想这更像是一个 python 问题而不是 django 问题,但我无法在其他任何地方复制这种行为,所以我将使用无法按预期工作的确切代码。
当我在 django 中处理一些动态表单时,我发现了这个工厂函数 sn-p:
def get_employee_form(employee):
"""Return the form for a specific Board."""
employee_fields = EmployeeFieldModel.objects.filter(employee = employee).order_by ('order')
class EmployeeForm(forms.Form):
def __init__(self, *args, **kwargs):
forms.Form.__init__(self, *args, **kwargs)
self.employee = employee
def save(self):
"Do the save"
for field in employee_fields:
setattr(EmployeeForm, field.name, copy(type_mapping[field.type]))
return type('EmployeeForm', (forms.Form, ), dict(EmployeeForm.__dict__))
[来自:http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/]
还有一件事我不明白,为什么返回修改后的 EmployeeForm 不起作用? 我的意思是这样的:
def get_employee_form(employee):
#[...]same function body as before
for field in employee_fields:
setattr(EmployeeForm, field.name, copy(type_mapping[field.type]))
return EmployeeForm
当我尝试返回修改后的类时,django 忽略了我的附加字段,但返回 type() 的结果效果很好。
【问题讨论】: