Welcome to django-html-cleaner’s documentation!

Quickstart

Install django-html-cleaner:

pip install django-html-cleaner

Then enable it in a Django project by adding django_html_cleaner to your INSTALLED_APPS in your Django settings.

Then use it:

from django_html_cleaner.models import SanitizedTextField

# in a Django model
field = SanitizedTextField()

Django settings

SanitizedCharField and SanitizedTextField can take an instance of django_html_cleaner.cleaner.Cleaner to set up how they will clean HTML on save.

An alternative way to set this up is to use your Django settings. In django.conf.settings, you can use the following settings to set up django-html-cleaner’s behavior:

HTML_CLEANER_ALLOWED_TAGS
A list of tags that will be allowed. If not set, all tags that are known HTML tags and are not special (script, html, etc) will be allowed.
HTML_CLEANER_ALLOWED_ATTRIBUTES
A list of attributes that will be allowed. If not set, all attributes that are not JavaScript-related (onclick, for example) will be allowed.
HTML_CLEANER_ALLOWED_STYLES
A list of styles that will be allowed. If not set, all styles are allowed.
HTML_CLEANER_PARENT_TAG
If set to a tag name, all input will be wrapped in this parent tag.

Classes

class django_html_cleaner.cleaner.Cleaner(allowed_tags=None, allowed_attributes=None, allowed_styles=None, create_parent=False)[source]

Cleans HTML to remove offending tags, attributes, or styles. Takes the following arguments:

allowed_tags:
If allowed_tags is not set, all valid HTML tags except script are accepted.
allowed_attributes:
If allowed_attributes is not set, all attributes are accepted except those that would trigger JavaScript.
allowed_styles:
If allowed_styles is not set, all styles are accepted.
create_parent:
Specify a tag to wrap the HTML in before cleaning. If left False, LXML will figure out what to do through black magic and fairy dust.

JavaScript is always removed.

clean(html)[source]

Clean the given HTML.

class django_html_cleaner.models.SanitizedCharField(cleaner=None, *args, **kwargs)[source]

Use anywhere you would use a CharField. Sanitizes HTML.

cleaner:
An instance of django_html_cleaner.cleaner.Cleaner(). Provide your own instance if you want to do more than just remove JavaScript and unknown/special HTML tags.
class django_html_cleaner.models.SanitizedTextField(cleaner=None, *args, **kwargs)[source]

Use anywhere you would use a TextField. Sanitizes HTML.

cleaner:
An instance of django_html_cleaner.cleaner.Cleaner(). Provide your own instance if you want to do more than just remove JavaScript and unknown/special HTML tags.