Wagtail CMS 如何在发布或保存为草稿之前验证一页的内容

Wagtail CMS how to validate the content of one page before publishing or saving it as draft

我正在尝试使用 Wagtail CMS 创建一个页面,每当我 save/publish 管理编辑器中的页面时它都会验证内容。

我要验证的内容是页面内3个SnippetChooserPanels的内容。基本上假设我有这 3 个片段:SnippetA、SnippetB 和 SnippetC,这些片段(或 Django 模型,因为它们确实如此)具有以下关系:

当用户saves/publishes我要验证的页面:

谢谢!

Wagtail 允许您通过 Page 模型上的 base_form_class 属性为每个 Page 模型自定义编辑表单。

这个引用的class必须是subclass的WagtailAdminPageForm。这是一个 Django Form 的核心,因此有一个 clean 方法允许在提交时进行额外的自定义验证以及保存步骤失败并提供每个字段的错误消息。

文档

代码示例models.py

from django import forms
from django.db import models

from wagtail.admin.edit_handlers import FieldPanel
from wagtail.admin.forms import WagtailAdminPageForm
from wagtail.core.models import Page
from wagtail.snippets.edit_handlers import SnippetChooserPanel


class CustomPageForm(WagtailAdminPageForm):

    def clean(self):
        cleaned_data = super().clean()

        # Make sure that the the snippets relate to each other correctly
        snippet_a = cleaned_data['snippet_a']
        snippet_b = cleaned_data['snippet_b']
        snippet_c = cleaned_data['snippet_c']

        # example validation only - you will need to work this out based on your exact requirements
        if snippet_a.pk is snippet_b.pk:
            self.add_error('snippet_a', 'The snippets must be different')
        if snippet_b.pk is snippet_c.pk:
            self.add_error('snippet_a', 'The snippets must be different')
        if snippet_c.pk is snippet_a.pk:
            self.add_error('snippet_a', 'The snippets must be different')
        if snippet_c.pk is snippet_b.pk:
            self.add_error('snippet_a', 'The snippets must be different')

        return cleaned_data


class EventPage(Page):
    # note: actual models.ForeignKey usage not added, just for the example
    snippet_a = models.ForeignKey()
    snippet_b = models.ForeignKey()
    snippet_c = models.ForeignKey()

    content_panels = [
        SnippetChooserPanel('snippet_a'),
        SnippetChooserPanel('snippet_b'),
        SnippetChooserPanel('snippet_c'),
    ]

    base_form_class = CustomPageForm