我正在使用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')
我希望验证错误会出现在管理界面中。在
我已经深入研究了wagtail的源代码,我想我找到了如何访问orderable的表单控件的方法。在
假设你有一个页面模型
对于某些可订购模型,它通过相关名称“test_page_field”链接到页面
^{pr2}$然后您可以在页面的clean方法中通过
self.formsets['test_page_field'].forms
来访问它,这是一个Django表单对象的列表,在这里可以进行常规检查,并且可以使用.add_error()
方法。相关的base_form_class
如下所示:我希望这有帮助。在
相关问题 更多 >
编程相关推荐