在Wagtail文档中,我找到了一个说明性示例,展示了如何自定义管理表单的行为并添加一些验证并保存特权:
from django import forms
import geocoder # not in Wagtail, for example only - http://geocoder.readthedocs.io/
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.admin.forms import WagtailAdminPageForm
from wagtail.core.models import Page
class EventPageForm(WagtailAdminPageForm):
address = forms.CharField()
def clean(self):
cleaned_data = super().clean()
# Make sure that the event starts before it ends
start_date = cleaned_data['start_date']
end_date = cleaned_data['end_date']
if start_date and end_date and start_date > end_date:
self.add_error('end_date', 'The end date must be after the start date')
return cleaned_data
def save(self, commit=True):
page = super().save(commit=False)
# Update the duration field from the submitted dates
page.duration = (page.end_date - page.start_date).days
# Fetch the location by geocoding the address
page.location = geocoder.arcgis(self.cleaned_data['address'])
if commit:
page.save()
return page
class EventPage(Page):
start_date = models.DateField()
end_date = models.DateField()
duration = models.IntegerField()
location = models.CharField(max_length=255)
content_panels = [
FieldPanel('title'),
FieldPanel('start_date'),
FieldPanel('end_date'),
FieldPanel('address'),
]
base_form_class = EventPageForm
全部及所有内容显示了如何在保存表单等之前确保日期字段设置正确。很好,我的问题是表单是否包含像这样的parental字段?:
class EventPage(Page):
start_date = models.DateField()
end_date = models.DateField()
duration = models.IntegerField()
location = models.CharField(max_length=255)
content_panels = [
FieldPanel('title'),
FieldPanel('start_date'),
FieldPanel('end_date'),
FieldPanel('address'),
InlinePanel('image_relations')
]
base_form_class = EventPageForm
class EventPageImageRelations(Orderable):
parent = ParentalKey(
EventPage,
related_name="image_relations",
on_delete=models.CASCADE
)
image = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.CASCADE,
related_name='+'
)
date = models.DateField()
panels = [
ImageChooserPanel('image'),
FieldPanel('date')
]
现在,假设您要在保存之前进行检查,以确保在start_date之后输入每个图像的指定日期。 我发现这具有挑战性,如何在外键关系的表单上获取价值!