如果在wagtail CMS中将'\ n'字符键入RichTextField,则验证程序的__call__
方法中会出现XML ParseError错误。
这里发生错误plain_text = ''.join(fromstring(value).itertext())
from xml.etree.ElementTree import fromstring
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
@deconstructible
class ProhibitBlankRichTextValidator:
"""
Validate that the incoming html-string contains plain text characters.
Common usage: Proper RichTextField validation
Reason:
Handling improper RichTextField validation by Wagtail 2.1:
https://github.com/wagtail/wagtail/issues/4549
"""
message = "This field is required."
def __init__(self, message=None):
if message is not None:
self.message = message
def __call__(self, value):
plain_text = ''.join(fromstring(value).itertext()) # Escape html tags
if not plain_text:
raise ValidationError(self.message)
富文本字段的值不能保证是完整的有效XML文档,因为它可以包含多个顶级元素,这在XML中是不允许的。如果要通过强制执行此操作的XML解析器运行该值,则需要首先将其包装在外部元素(如<rich-text>...</rich-text>
)中。