from django import newforms as forms from django.conf import settings from django.newforms.fields import EMPTY_VALUES from django.utils.translation import ugettext as _, ungettext from utils.BeautifulSoup import BeautifulSoup, Comment class CleanCharField(forms.CharField): valid_tags= settings.VALID_TAGS.split() valid_attrs= settings.VALID_ATTRS.split() def clean(self, value): """ Checks that the given string has no profanities in it. This does a simple check for whether each profanity exists within the string, so 'fuck' will catch 'motherfucker' as well. Raises a ValidationError such as: Watch your mouth! The words "f--k" and "s--t" are not allowed here. """ value= value.lower() # normalize words_seen= [w for w in settings.PROFANITIES_LIST if w in value] if words_seen: from django.utils.text import get_text_list plural= len(words_seen) raise forms.ValidationError, ungettext("Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], _('and')) """ Cleans non-allowed HTML from the input """ value= super(CleanCharField, self).clean(value) 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 self.valid_tags: tag.hidden= True tag.attrs= [(attr, val) for attr, val in tag.attrs if attr in self.valid_attrs] return soup.renderContents().decode('utf8') settings.py: PROFANITIES_LIST = ('asshat', 'asshead', 'asshole', 'cunt', 'fuck', 'gook', 'nigger', 'shit',) VALID_TAGS= 'p i strong b u a h1 h2 h3 pre br img' VALID_ATTRS= 'href src'