Skip to content

Instantly share code, notes, and snippets.

@jab3z
Last active March 13, 2017 16:33
Show Gist options
  • Save jab3z/8cdaa089ef995b76f9c16e78ab248f27 to your computer and use it in GitHub Desktop.
Save jab3z/8cdaa089ef995b76f9c16e78ab248f27 to your computer and use it in GitHub Desktop.
snake case
import re
from django.utils.text import force_text
from django.utils.safestring import mark_safe
from django.utils.functional import allow_lazy
def snake_case(value):
"""
Converts spaces to underscore. Removes characters that
aren't alphanumerics, underscores, or hyphens. Converts to lowercase.
Also strips leading and trailing whitespace.
"""
value = force_text(value)
value = re.sub('[^\w\s-]', '', value).strip().lower()
return mark_safe(re.sub('[-\s]+', '_', value))
snake_case = allow_lazy(snake_case)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment