我猜这是一个比django更多的python问题,但我无法在其他任何地方复制此行为,所以我将使用不起作用的确切代码预期。返回修改后的类和使用类型之间的区别()
我是工作在Django中一些动态的形式,当我发现这个工厂函数摘录:
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的类忽略我的其他字段,但返回类型()的结果完美。
我认为dict(EmployeeForm .__ dict__)的原因是之前的forms.Form用于返回一个DictProxy而不是一个字典。 – agiliq 2009-10-21 09:32:56