是否有方法在WagtailCMS的InlinePanel中对相关医嘱内容执行验证?

2024-10-17 00:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Wagtail CMS,我需要对我的Orderable模型进行一些验证。例如,确保最多填充一个字段。在

通常,我会覆盖Django模型的clean(self)方法,但是在该方法中调用super().clean()返回{}。我仍然可以使用self.field_name来访问字段,并且提升ValidationError仍然可以阻止模型的创建,但是它不会在管理界面中显示导致模型错误的字段。在

我已经尝试重写clean方法,它停止提交模型,但不会在接口上显示错误

我尝试过遵循this part of the guide,但是那里的clean方法甚至没有调用Orderable。在

这是我的clean方法的示例

def clean(self):
    super().clean()
    has_image =  self.image is not None
    has_video = self.video_url is not None

    if has_image == has_video:
        raise ValidationError('Either a video or an image must be set')

我希望验证错误会出现在管理界面中。在


Tags: 方法模型imageselfcleannone界面is
1条回答
网友
1楼 · 发布于 2024-10-17 00:26:35

我已经深入研究了wagtail的源代码,我想我找到了如何访问orderable的表单控件的方法。在

假设你有一个页面模型

class TestPage(Page):

    testPageTitle = RichTextField(blank=True, max_length=250)

    content_panels = Page.content_panels + [
    FieldPanel('testPageTitle'),
    InlinePanel('test_page_field')
    ]

    base_form_class = TestPageForm

对于某些可订购模型,它通过相关名称“test_page_field”链接到页面

^{pr2}$

然后您可以在页面的clean方法中通过self.formsets['test_page_field'].forms来访问它,这是一个Django表单对象的列表,在这里可以进行常规检查,并且可以使用.add_error()方法。相关的base_form_class如下所示:

class TestPageForm(WagtailAdminPageForm):

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

    #loop over linked orderables
    for form in self.formsets['test_page_field'].forms:

        #check first if form is valid, otherwise cleaned_data will not be accesible/set
        if form.is_valid():
            cleaned_form_data = form.clean()
            testPageFieldFieldTitle = cleaned_form_data.get('testPageFieldFieldTitle')

            #execute some validation condition, and raise the error if it fails
            if testPageFieldFieldTitle is None:
                form.add_error('testPageFieldFieldTitle', 'please dont leave me empty')

    return cleaned_data

我希望这有帮助。在

相关问题 更多 >