brack3t/django-braces

UntrustedForm stripping html tags from inputs.

bukowa opened this issue · 1 comments

Is that a mixin that can be added to django-braces based on mozilla bleach https://github.com/mozilla/bleach? I may provide an PR but i would like to ask first.

import bleach
class UntrustedFormMixin:
    """
    Strip html tags from inputs.
    """

    html_strip_fields = []  # list of field names to clean html from
    html_allowed_tags = []
    html_allowed_attributes = {}
    html_allowed_css_styles = []
    html_allowed_protocols = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # https://bleach.readthedocs.io/en/latest/clean.html#bleach.sanitizer.Cleaner
        self.HTML_cleaner = bleach.Cleaner(
            tags=self.html_allowed_tags,
            attributes=self.html_allowed_attributes,
            styles=self.html_allowed_css_styles,
            protocols=self.html_allowed_protocols,
        )

    def clean(self):
        super().clean()
        # clean HTML
        for key in self.html_strip_fields:
            value = self.cleaned_data.get(key)
            if value:
                self.cleaned_data[key] = self.HTML_cleaner.clean(value)
        return self.cleaned_data

closing very old issues