我有这个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)
但它不起作用,也许有人知道该怎么做?
答案 0 :(得分:1)
为页面定义自定义表单,并在clean
方法中添加验证逻辑:
答案 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