(custom_page_models)= # 定义自定义基础页面模型 自定义基础页面模型让你可以定义应用专属的字段,使它们能在所有具体(子类化的)页面模型上可用并可查询,而不必承担多级继承的开销。自定义基础页面模型需要在运行 Wagtail 的数据迁移之前完成额外配置,因此只支持新建的项目,以及正在加入 Wagtail 的既有 Django 项目。 ```{warning} 该功能目前处于实验阶段。某些第三方包可能不兼容。 ``` ````{note} 我们已发布了一个按这些说明改用自定义基础页面模型的现成 Wagtail 项目模板:[wagtail-custom-base-page-template](https://github.com/wagtail/wagtail-custom-base-page-template)。要使用该模板建立新项目,请运行: ```bash wagtail start mysite --template=https://github.com/wagtail/wagtail-custom-base-page-template/archive/main.zip ``` ```` 按 [](quick_install) 或 [](/getting_started/integrating_into_django) 所述创建好 Wagtail 项目之后、但在运行 `python manage.py migrate` 之前,请运行 `python manage.py startapp basepage` 创建一个新应用来容纳基础页面模型,并把 `"basepage"` 添加到 `INSTALLED_APPS`。建议专门用一个应用只放基础页面模型,以尽量降低出现循环导入的可能。 在 `basepage/models.py` 中,定义一个继承 {class}`~wagtail.models.AbstractPage` 的页面模型,包含你想要的字段 —— 例如: ```python from django.db import models from wagtail.models import AbstractPage class BasePage(AbstractPage): category = models.CharField(max_length=100, blank=True) review_date = models.DateField(blank=True, null=True) promote_panels = AbstractPage.promote_panels + ["category", "review_date"] ``` ```{note} `AbstractPage` 提供 {class}`~wagtail.models.Page` 的所有标准字段,但 `show_in_menus`、`seo_title` 和 `search_description` 除外。这意味着 {meth}`~wagtail.query.PageQuerySet.in_menu` 和 {meth}`~wagtail.query.PageQuerySet.not_in_menu` 方法将无法工作。要在页面模型中包含“在菜单中显示”标志,请让你的类同时继承 `AbstractPage` 和 {class}`~wagtail.models.ShowInMenusMixin`。要包含 `Page` 的所有默认字段,请同时继承 `AbstractPage` 和 {class}`~wagtail.models.DefaultBasePageMixin`。 ``` 在项目的设置文件中添加 `WAGTAIL_PAGE_MODEL` 设置,其值为基础页面模型的点分 {attr}`~django.db.models.Options.label`(需带上应用名限定): ```python WAGTAIL_PAGE_MODEL = "basepage.BasePage" ``` 如果你还有其他定义了页面模型的应用(例如默认项目模板中的 `home` 应用),请先把它们从 `INSTALLED_APPS` 中临时注释掉。然后运行: ```sh python manage.py makemigrations ``` 这会在 `basepage/migrations/` 中创建一个初始迁移。现在需要编辑它,以确保它在 Wagtail 自己的迁移之前运行。从 `dependencies` 列表中移除 `"wagtailcore"` 条目。然后,在针对 `BasePage` 的 `migrations.CreateModel` 操作中,删除 `"latest_revision"`、`"live_revision"`、`"locale"` 和 `"translation_key"` 的字段定义,以及 `("translation_key", "locale")` 的 `unique_together` 约束,因为它们引用的其他模型在迁移序列中更晚才被创建。 接下来,我们必须创建一个迁移来添加并填充 `locale` 和 `translation_key` 字段。运行: ```sh python manage.py makemigrations --empty basepage ``` 并把生成的迁移文件重命名为 `0002_bootstrap_page_model.py`。按如下方式编辑该文件: ```python from django.db import migrations from wagtail.models import ( BootstrapLocaleField, BootstrapTranslatableModel, BootstrapTranslationKeyField, ) class Migration(migrations.Migration): # 保留自动生成迁移中已有的依赖列表 dependencies = [ ("basepage", "0001_initial"), ("wagtailcore", "0097_baselogentry_uuid_action_timestamp_indexes"), ] operations = [ BootstrapLocaleField("basepage.BasePage"), BootstrapTranslationKeyField("basepage.BasePage"), BootstrapTranslatableModel("basepage.BasePage"), ] ``` 现在我们创建最后一个迁移,为页面模型添加其余字段和约束。运行: ```sh python manage.py makemigrations basepage ``` 这会产出一个提示,询问如何处理 `locale` 字段变为非空的情况: ```console It is impossible to change a nullable field 'locale' on basepage to non-nullable without providing a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation. 3) Quit and manually define a default value in models.py. Select an option: ``` 请选择选项 2("Ignore for now"),因为这已由前一个迁移处理了。把生成的迁移文件重命名为 `0003_finalize_page_model.py`。 现在我们可以更新任何定义了页面模型的既有应用(例如默认项目模板中的 `home` 应用),让它们继承新的 `BasePage` 模型。首先,取消 `INSTALLED_APPS` 列表中该应用条目的注释。接着,更新该应用的 `models.py`,把所有对默认 `Page` 模型的引用替换为 `BasePage`: ```python from django.db import models from basepage.models import BasePage class HomePage(BasePage): pass ``` 该应用的迁移文件也必须做相应修改。对于所有迁移都是自动生成的 schema 迁移的应用,可以删除现有迁移并用 `makemigrations` 命令重新生成一个;但 `home` 应用不属于这种情况。`home` 应用所需的修改如下: 在 `0001_initial.py` 中,`page_ptr` 字段应重命名为 `basepage_ptr`,并应指向 `basepage.BasePage` 而不是 `wagtailcore.Page`,`bases` 应变为 `("basepage.basepage",)`: ```python ( migrations.CreateModel( name="HomePage", fields=[ ( "basepage_ptr", models.OneToOneField( on_delete=models.CASCADE, parent_link=True, auto_created=True, primary_key=True, serialize=False, to="basepage.BasePage", ), ), ], options={ "abstract": False, }, bases=("basepage.basepage",), ), ) ``` 在 `0002_create_homepage.py` 中,对 `Page` 模型和内容类型的查找应改为 `BasePage`: ```python # 旧代码 Page = apps.get_model("wagtailcore.Page") # 新代码 Page = apps.get_model("basepage.BasePage") ``` ```python # 旧代码 page_content_type = ContentType.objects.get(model="page", app_label="wagtailcore") # 新代码 page_content_type = ContentType.objects.get(model="basepage", app_label="basepage") ``` 其他引用默认 `Page` 模型的项目代码也应改为引用 `BasePage`,包括默认项目模板中的 `search/views.py`。 现在用 `python manage.py migrate` 应用迁移应当能成功,并允许你继续完成项目其余部分的配置。在定义后续页面类型时,应继承 `BasePage` 而不是默认的 `Page` 模型。这样这些页面类型就会继承基础页面模型上定义的字段,并且由于这些字段是真正由所有页面类型共享的(而不是像定义在抽象模型上那样为每种类型各复制一份),因此可以用 ORM 查询在所有页面类型上查询它们,例如: ```python BasePage.objects.filter(category="sport").specific() ``` ## 使用 contrib 应用时的注意事项 Wagtail 的 [](form_builder) 应用提供 `AbstractForm` 和 `AbstractEmailForm` 页面类。它们继承默认的 `Page` 模型,在使用自定义基础页面模型时不可用。此时应改用[混合类](form_builder_mixins)。例如,不要这样: ```python from wagtail.contrib.forms.models import AbstractForm class FormPage(AbstractForm): # ... ``` 而应这样 ```python from wagtail.contrib.forms.models import FormMixin class FormPage(FormMixin, BasePage): # ... ``` 以及不要这样 ```python from wagtail.contrib.forms.models import AbstractEmailForm class FormPage(AbstractEmailForm) # ... ``` 而应这样 ```python from wagtail.contrib.forms.models import EmailFormMixin, FormMixin class FormPage(EmailFormMixin, FormMixin, BasePage) # ... ``` 同样,[`wagtail.contrib.routable_page`](routable_page_mixin) 应用提供 `RoutablePage` 类,它继承默认的 `Page` 模型,在使用自定义基础页面模型时不可用;不过 `RoutablePageMixin` 仍可使用。 ## 示例用例 有很多场景适合采用自定义基础页面模型。下面举几个例子加以说明: - 添加一个站点级的 `include_in_sitemap` 字段,以便排除任意页面。 - 为 CMS 用户设置一个内部“备注”字段,使他们能直接在 CMS 中记录自己的工作。 - 站点级的[内容个性化](content_personalization),其中每个页面都可以指定目标受众或目标。 ## 另见 [](reusable_app_base_page)