在 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
总而言之,它显示了如何确保在保存表单之前设置正确的日期字段等等。太好了,我的问题是表单是否包含 parentalkey 字段?像这样:
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 之后输入每个图像的指定日期。我发现这具有挑战性,如何获得外键关系表单上的值!