from bs4 import BeautifulSoup
from bs4.element import Tag
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
@deconstructible
class HtmlValidator:
def __init__(self, tags=()):
self.tags = tags
def validate(self, node):
if isinstance(node, Tag):
if node.name not in self.tags:
raise ValidationError(f'Tag {node.name} is not a valid tag')
for child in node:
self.validate(child)
def __call__(self, value):
soup = BeautifulSoup(value, 'html.parser')
for child in soup:
self.validate(soup)
1条答案
按热度按时间fkvaft9z1#
我们可以创建一个只允许某些标签的验证器,例如 BeautifulSoup:
然后我们可以将这样的验证器添加到模型中: