如何 return 一些错误而不是在 wagtail 中保存页面?

How to return some error instead of page saving in wagtail?

我有这个 wagtail 页面模型:

from wagtail.wagtailcore.models import Page
...
class PhotoEventPage(Page):
    photos = models.FileField()
    description = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('photos'),
        FieldPanel('description')
    ]

我不想在 photos 扩展名不是 zip 时保存此页面,所以在这种情况下我想在 wagtail 管理中显示错误。所以我试过了:

class PhotoEventPage(Page):
    photos = models.FileField()
    description = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('photos'),
        FieldPanel('description')
    ]

    def save(self, *args, **kwargs):
        if self.photos.file.name.split('.')[-1] != 'zip':
            return ValidationError('test')
        return super().save(*args, **kwargs)

但是它不起作用,也许有人知道该怎么做?

为页面定义自定义表单,并在其中的 clean 方法中添加验证逻辑:

http://docs.wagtail.io/en/v1.13.1/advanced_topics/customisation/page_editing_interface.html#customising-generated-forms

感谢 gasman。如文档中所述,我需要在模型上设置 base_form_class

from wagtail.wagtailadmin.forms import WagtailAdminPageForm


class PhotoEventPageForm(WagtailAdminPageForm):

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

        if (cleaned_data.get('photos') and
                cleaned_data['photos'].name.split('.')[-1] != 'zip'):
            self.add_error('photos', 'Расширение должно быть zip')

        return cleaned_data


class PhotoEventPage(Page):
    photos = models.FileField()
    description = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('photos'),
        FieldPanel('description')
    ]
    base_form_class = PhotoEventPageForm