如何在witctail中返回一些错误而不是页面保存?

时间:2018-02-18 20:40:44

标签: python 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 admin中显示错误。所以我试过了:

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)

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

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

感谢 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