Skip to main content
 首页 » 编程设计

python之为什么 Django 使用 BaseForm

2024年09月03日35JustinYoung

我想我终于弄明白他们需要使用这个 DeclarativeFieldsMetaclass(将类字段转换为实例变量并使用有序/排序的字典维护它们的顺序)。但是,我仍然不太清楚为什么他们选择使用 BaseForm 而不是直接在 Form 类中实现所有内容?

他们 left a comment ,

class Form(BaseForm): 
    "A collection of Fields, plus their associated data." 
    # This is a separate class from BaseForm in order to abstract the way 
    # self.fields is specified. This class (Form) is the one that does the 
    # fancy metaclass stuff purely for the semantic sugar -- it allows one 
    # to define a form using declarative syntax. 
    # BaseForm itself has no way of designating self.fields. 

但是我不是很懂。 “为了抽象指定 self.fields 的方式”——但是 Python 在 Form.__init__ 之前调用了 DeclarativeFieldsMetaclass.__new__,所以他们可以充分利用 self.fields inside Form.__init__ 原样;为什么他们需要额外的抽象层?

请您参考如下方法:

我认为原因很简单,单独使用 BaseForm 你不能使用声明语法定义字段,即

class MyForm(Form): 
    field_xxx = form.TextField(...) 
    field_nnn _ form.IntegerField(...) 

对于这样的事情,应该有一个元类DeclarativeFieldsMetaclass,它只在表单中设置,他们这样做是因为

This is a separate class from BaseForm in order to abstract the way, self.fields is specifie

所以现在您可以编写 WierdForm 类,其中可以以某种奇怪的方式定义字段,例如将参数传递给类对象,重点是所有 API 都在 BaseForm 中,而 Form 类只是提供了一个易于定义的字段。

总结:IMO django 更喜欢引入另一层,以便在需要时可以实现不同类型的字段声明,至少它保持表单的非核心功能独立。