Skip to content

Instantly share code, notes, and snippets.

@mattlong
Created January 6, 2014 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattlong/8290178 to your computer and use it in GitHub Desktop.
Save mattlong/8290178 to your computer and use it in GitHub Desktop.
WebsafeCharField for Django REST Framework
class WebsafeCharField(serializers.CharField):
"""
Like a regular CharField but does not allow certain characters.
cannot contain / or \ or non-printable ASCII (0-31, 127)
cannot contain non-characters from Unicode Plane 1 (U+FFFE and U+FFFF)
cannot contain characters from Unicode Planes 2-16 (U+10000 through U+10FFFF)
"""
default_error_messages = {
'contains_unallowed_chars': _(r'Cannot contain non-printable ASCII, /, \, U+FFFE, U+FFFF, or U+10000 through U+10FFFF.'),
}
def __init__(self, *args, **kwargs):
super(WebsafeCharField, self).__init__(*args, **kwargs)
self.unallowed_char_regex = re.compile(u'[\x00-\x1f\x7f/\\\\\uFFFE-\U0010FFFF]', re.UNICODE)
def from_native(self, value):
value = super(WebsafeCharField, self).from_native(value)
if isinstance(value, basestring):
match = self.unallowed_char_regex.search(value)
if match:
raise ValidationError(self.error_messages['contains_unallowed_chars'])
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment