Уже поздно, но вы можете попробовать Bleach , под капотом он использует html5lib, и вы также получите балансировку тегов.
Вот полный фрагмент:
settings.py
BLEACH_VALID_TAGS = ['p', 'b', 'i', 'strike', 'ul', 'li', 'ol', 'br',
'span', 'blockquote', 'hr', 'a', 'img']
BLEACH_VALID_ATTRS = {
'span': ['style', ],
'p': ['align', ],
'a': ['href', 'rel'],
'img': ['src', 'alt', 'style'],
}
BLEACH_VALID_STYLES = ['color', 'cursor', 'float', 'margin']
app / forms.py
import bleach
from django.conf import settings
class MyModelForm(forms.ModelForm):
myfield = forms.CharField(widget=MyWYSIWYGEditor)
class Meta:
model = MyModel
def clean_myfield(self):
myfield = self.cleaned_data.get('myfield', '')
cleaned_text = bleach.clean(myfield, settings.BLEACH_VALID_TAGS, settings.BLEACH_VALID_ATTRS, settings.BLEACH_VALID_STYLES)
return cleaned_text #sanitize html
Вы можете прочитать документы для отбеливания , чтобы вы могли адаптировать его к своемунеобходимо.