自定义文档模型

可以使用另一个 Document 模型来添加自定义行为和 额外字段。

要在项目中做到这一点,你需要完成以下步骤:

  • 创建一个继承 wagtail.documents.models.AbstractDocument 的新文档模型。你要添加的额外字段就放在这里。

  • 把 WAGTAILDOCS_DOCUMENT_MODEL 指向这个新模型。

下面是一个例子:

# models.py
from django.db import models

from wagtail.documents.models import Document, AbstractDocument


class CustomDocument(AbstractDocument):
    # 自定义字段示例:
    source = models.CharField(max_length=255, blank=True, null=True)

    admin_form_fields = Document.admin_form_fields + (
        # 把所有自定义字段名加进来,让它们出现在表单中:
        "source",
    )

然后在你的设置模块中:

# 确保把 app_label 替换成你放置自定义
# 模型的那个应用。
WAGTAILDOCS_DOCUMENT_MODEL = "app_label.CustomDocument"

备注

从内置文档模型迁移:

把已有站点改为使用自定义文档模型时,不会有任何文档 被自动复制到新模型。把旧文档复制到 新模型需要手动完成,用的是 数据迁移。

那些引用内置文档模型的模板会继续 像以前一样正常工作

引用文档模型

wagtail.documents.get_document_model()

Get the document model from the WAGTAILDOCS_DOCUMENT_MODEL setting. Defaults to the standard wagtail.documents.models.Document model if no custom model is defined.

wagtail.documents.get_document_model_string()

Get the dotted app.Model name for the document model as a string. Useful for developers making Wagtail plugins that need to refer to the document model, such as in foreign keys, but the model itself is not required.