Skip to content

Django 4.0 compatibility: smart_str #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sanitizer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
VERSION = (0, 1, 4)
VERSION = (0, 1, 6)

from .decorators import sanitize
3 changes: 1 addition & 2 deletions sanitizer/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ class sanitize(object):


def __init__(self, tags=bleach.ALLOWED_TAGS,
attributes=bleach.ALLOWED_ATTRIBUTES, styles=[], strip=False,
attributes=bleach.ALLOWED_ATTRIBUTES, strip=False,
strip_comments=True):
self.kwargs = {
'tags': tags,
'attributes': attributes,
'styles': styles,
'strip': strip,
'strip_comments': strip_comments,
}
Expand Down
5 changes: 2 additions & 3 deletions sanitizer/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ class SanitizedCharField(forms.CharField):
A subclass of CharField that escapes (or strip) HTML tags and attributes.
"""
def __init__(self, allowed_tags=[], allowed_attributes=[],
allowed_styles=[], strip=False, *args, **kwargs):
strip=False, *args, **kwargs):
self._allowed_tags = allowed_tags
self._allowed_attributes = allowed_attributes
self._allowed_styles = allowed_styles
self._strip = strip
super(SanitizedCharField, self).__init__(*args, **kwargs)

def clean(self, value):
value = super(SanitizedCharField, self).clean(value)
return bleach.clean(value, tags=self._allowed_tags,
attributes=self._allowed_attributes,
styles=self._allowed_styles, strip=self._strip)
strip=self._strip)
17 changes: 9 additions & 8 deletions sanitizer/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_text as smart_unicode
try:
from django.utils.encoding import smart_str as smart_unicode
except ImportError:
from django.utils.encoding import smart_text as smart_unicode
else:
from django.utils.encoding import smart_unicode

Expand All @@ -13,45 +16,43 @@
class SanitizedCharField(models.CharField):

def __init__(self, allowed_tags=[], allowed_attributes=[],
allowed_styles=[], strip=False,
strip=False,
*args, **kwargs):
self._sanitizer_allowed_tags = allowed_tags
self._sanitizer_allowed_attributes = allowed_attributes
self._sanitizer_allowed_styles = allowed_styles
self._sanitizer_strip = strip
super(SanitizedCharField, self).__init__(*args, **kwargs)

def to_python(self, value):
value = super(SanitizedCharField, self).to_python(value)
value = bleach.clean(value, tags=self._sanitizer_allowed_tags,
attributes=self._sanitizer_allowed_attributes,
styles=self._sanitizer_allowed_styles, strip=self._sanitizer_strip)
strip=self._sanitizer_strip)
return smart_unicode(value)


class SanitizedTextField(models.TextField):

def __init__(self, allowed_tags=[], allowed_attributes=[],
allowed_styles=[], strip=False,
strip=False,
*args, **kwargs):
self._sanitizer_allowed_tags = allowed_tags
self._sanitizer_allowed_attributes = allowed_attributes
self._sanitizer_allowed_styles = allowed_styles
self._sanitizer_strip = strip
super(SanitizedTextField, self).__init__(*args, **kwargs)

def to_python(self, value):
value = super(SanitizedTextField, self).to_python(value)
value = bleach.clean(value, tags=self._sanitizer_allowed_tags,
attributes=self._sanitizer_allowed_attributes,
styles=self._sanitizer_allowed_styles, strip=self._sanitizer_strip)
strip=self._sanitizer_strip)
return smart_unicode(value)

def get_prep_value(self, value):
value = super(SanitizedTextField, self).get_prep_value(value)
value = bleach.clean(value, tags=self._sanitizer_allowed_tags,
attributes=self._sanitizer_allowed_attributes,
styles=self._sanitizer_allowed_styles, strip=self._sanitizer_strip)
strip=self._sanitizer_strip)
return value


Expand Down
28 changes: 12 additions & 16 deletions sanitizer/templatetags/sanitizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,15 @@

ALLOWED_TAGS = getattr(settings, 'SANITIZER_ALLOWED_TAGS', [])
ALLOWED_ATTRIBUTES = getattr(settings, 'SANITIZER_ALLOWED_ATTRIBUTES', [])
ALLOWED_STYLES = getattr(settings, 'SANITIZER_ALLOWED_STYLES', [])

register = template.Library()


@stringfilter
def sanitize(value):
'''
Sanitizes strings according to SANITIZER_ALLOWED_TAGS,
SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in
Sanitizes strings according to SANITIZER_ALLOWED_TAGS and
SANITIZER_ALLOWED_ATTRIBUTES variables in
settings.

Example usage:
Expand All @@ -32,7 +31,7 @@ def sanitize(value):
if isinstance(value, basestring):
value = bleach.clean(value, tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES, strip=False)
strip=False)
return value

register.filter('escape_html', sanitize)
Expand All @@ -41,8 +40,8 @@ def sanitize(value):
@stringfilter
def strip_filter(value):
'''
Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS,
SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in
Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS
and SANITIZER_ALLOWED_ATTRIBUTES variables in
settings.

Example usage:
Expand All @@ -54,7 +53,7 @@ def strip_filter(value):
if isinstance(value, basestring):
value = bleach.clean(value, tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES, strip=True)
strip=True)
return value

register.filter('strip_html', strip_filter)
Expand All @@ -72,7 +71,6 @@ def sanitize_allow(value, args=''):
if isinstance(value, basestring):
allowed_tags = []
allowed_attributes = []
allowed_styles = []

args = args.strip().split(';')
if len(args) > 0:
Expand All @@ -88,11 +86,10 @@ def sanitize_allow(value, args=''):


@register.simple_tag
def escape_html(value, allowed_tags=[], allowed_attributes=[],
allowed_styles=[]):
def escape_html(value, allowed_tags=[], allowed_attributes=[]):
"""
Template tag to sanitize string values. It accepts lists of
allowed tags, attributes or styles in comma separated string or list format.
allowed tags or attributes in comma separated string or list format.

For example:

Expand All @@ -111,16 +108,15 @@ def escape_html(value, allowed_tags=[], allowed_attributes=[],
if isinstance(value, basestring):
value = bleach.clean(value, tags=allowed_tags,
attributes=allowed_attributes,
styles=allowed_styles, strip=False)
strip=False)
return value


@register.simple_tag
def strip_html(value, allowed_tags=[], allowed_attributes=[],
allowed_styles=[]):
def strip_html(value, allowed_tags=[], allowed_attributes=[]):
"""
Template tag to strip html from string values. It accepts lists of
allowed tags, attributes or stylesin comma separated string or list format.
allowed tags or attributes in comma separated string or list format.

For example:

Expand All @@ -139,5 +135,5 @@ def strip_html(value, allowed_tags=[], allowed_attributes=[],
if isinstance(value, basestring):
value = bleach.clean(value, tags=allowed_tags,
attributes=allowed_attributes,
styles=allowed_styles, strip=True)
strip=True)
return value
15 changes: 7 additions & 8 deletions sanitizer/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,21 @@

ALLOWED_TAGS = ['a']
ALLOWED_ATTRIBUTES = ['href', 'style']
ALLOWED_STYLES = ['width']


class TestingModel(models.Model):
test_field = SanitizedCharField(max_length=255, allowed_tags=ALLOWED_TAGS,
allowed_attributes=ALLOWED_ATTRIBUTES, allowed_styles=ALLOWED_STYLES)
allowed_attributes=ALLOWED_ATTRIBUTES)


class TestingTextModel(models.Model):
test_field = SanitizedTextField(allowed_tags=ALLOWED_TAGS,
allowed_attributes=ALLOWED_ATTRIBUTES, allowed_styles=ALLOWED_STYLES)
allowed_attributes=ALLOWED_ATTRIBUTES)


class TestForm(forms.Form):
test_field = SanitizedFormField(allowed_tags=['a'],
allowed_attributes=['href', 'style'], allowed_styles=['width'])
allowed_attributes=['href', 'style'])


class SanitizerTest(TestCase):
Expand Down Expand Up @@ -70,17 +69,17 @@ def test_SanitizedFormField(self):
def test_escape_html(self):
html = '<a href="" class="" style="width: 200px; height: 400px">foo</a><em></em>'
self.assertEqual(escape_html(html, allowed_tags='a',
allowed_attributes='href,style', allowed_styles='width'),
allowed_attributes='href,style'),
'<a href="" style="width: 200px;">foo</a>&lt;em&gt;&lt;/em&gt;')
self.assertEqual(escape_html(html, allowed_tags=['a'],
allowed_attributes=['href', 'style'], allowed_styles=['width']),
allowed_attributes=['href', 'style']),
'<a href="" style="width: 200px;">foo</a>&lt;em&gt;&lt;/em&gt;')

def test_strip_html(self):
html = '<a href="" class="" style="width: 200px; height: 400px">foo</a><em></em>'
self.assertEqual(strip_html(html, allowed_tags='a',
allowed_attributes='href,style', allowed_styles='width'),
allowed_attributes='href,style'),
'<a href="" style="width: 200px;">foo</a>')
self.assertEqual(strip_html(html, allowed_tags=['a'],
allowed_attributes=['href', 'style'], allowed_styles=['width']),
allowed_attributes=['href', 'style']),
'<a href="" style="width: 200px;">foo</a>')
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

setup(
name='django-html_sanitizer',
version='0.1.5',
version='0.1.7',
author='Selwin Ong',
author_email='[email protected]',
packages=['sanitizer'],
Expand All @@ -16,7 +16,7 @@
long_description=open('README.rst').read(),
zip_safe=False,
include_package_data=True,
install_requires=['django', 'bleach'],
install_requires=['django', 'bleach>=6'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
Expand Down