rich_text.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from __future__ import annotations
  2. from django.utils.safestring import mark_safe
  3. import nh3
  4. _ALLOWED_TAGS = {
  5. "p", "br", "strong", "b", "em", "i", "u", "s",
  6. "ul", "ol", "li", "blockquote", "pre", "code",
  7. "h1", "h2", "h3", "h4", "h5", "h6",
  8. "a", "img", "div", "span",
  9. }
  10. _ALLOWED_ATTRIBUTES = {
  11. "a": {"href", "title"},
  12. "img": {"src", "alt", "title", "width", "height"},
  13. "p": {"style"},
  14. "div": {"style"},
  15. "span": {"style"},
  16. }
  17. _CLEAN_CONTENT_TAGS = {"script", "style", "iframe", "object", "embed", "svg", "math"}
  18. _ALLOWED_URL_SCHEMES = {"http", "https", "mailto", "tel"}
  19. _ALLOWED_STYLE_PROPERTIES = {"text-align"}
  20. _CLEANER = nh3.Cleaner(
  21. tags=_ALLOWED_TAGS,
  22. attributes=_ALLOWED_ATTRIBUTES,
  23. clean_content_tags=_CLEAN_CONTENT_TAGS,
  24. url_schemes=_ALLOWED_URL_SCHEMES,
  25. filter_style_properties=_ALLOWED_STYLE_PROPERTIES,
  26. link_rel="noopener noreferrer",
  27. url_relative="pass_through",
  28. )
  29. def sanitize_rich_html(value: str | None) -> str | None:
  30. """Return safe persisted HTML while preserving the field's None semantics."""
  31. if value is None:
  32. return None
  33. return _CLEANER.clean(str(value))
  34. def render_rich_html(value: str | None):
  35. """Return a SafeString only after the same server-side allowlist sanitizer."""
  36. return mark_safe(sanitize_rich_html(value) or "")