Navigation Menu

Skip to content

Commit

Permalink
Allow users to add more elements
Browse files Browse the repository at this point in the history
  • Loading branch information
JordanReiter committed Jun 22, 2011
1 parent 2f49d57 commit 6d869f1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 7 additions & 1 deletion safehtmlform/fields.py
Expand Up @@ -5,10 +5,16 @@
class SafeHTMLField(forms.CharField):
help_text=_("This field allows the use of the following HTML tags: %(tags)s." % {'tags': acceptable_elements})
widget=forms.widgets.Textarea()

def __init__(self, *args, **kwargs):
self.acceptable_elements = acceptable_elements
additional_elements = kwargs.pop("additional_elements", None)
if additional_elements:
self.acceptable_elements += additional_elements

def clean(self, value):
"""
Cleans non-allowed HTML from the input.
"""
value = super(SafeHTMLField, self).clean(value)
return sanitize_html(value)
return sanitize_html(value, elements=self.acceptable_elements)
4 changes: 2 additions & 2 deletions safehtmlform/utils.py
Expand Up @@ -22,13 +22,13 @@ def sanitize_attrs(attrs):
return sanitized_attrs


def sanitize_html(value):
def sanitize_html(value, elements=acceptable_elements):
soup = BeautifulSoup(value)
for comment in soup.findAll(
text=lambda text: isinstance(text, Comment)):
comment.extract()
for tag in soup.findAll(True):
if tag.name not in acceptable_elements:
if tag.name not in elements:
tag.hidden = True
tag.attrs = sanitize_attrs(tag.attrs)
return soup.renderContents().decode('utf8').replace('javascript:', '')

0 comments on commit 6d869f1

Please sign in to comment.