Skip to content

Instantly share code, notes, and snippets.

@mgd020
Created April 11, 2017 23:54
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 mgd020/b6ca52e7d0d887fd93c7e0b3e86805f8 to your computer and use it in GitHub Desktop.
Save mgd020/b6ca52e7d0d887fd93c7e0b3e86805f8 to your computer and use it in GitHub Desktop.
Translate django url strings by slugs
from __future__ import absolute_import, division, print_function, unicode_literals
import re
from django.utils import six
from django.utils.functional import lazy, SimpleLazyObject
from django.utils.translation import ugettext
URL_SLUG_RE = SimpleLazyObject(lambda: re.compile(r'^[a-zA-Z0-9\-]+$'))
URL_DELIMS_RE = SimpleLazyObject(lambda: re.compile(r'(\^?)(?<=\^|/)?(?P<slug>[a-zA-Z0-9\-]+)(?=/|$)'))
def ugeturl(url):
return ''.join(ugettext(part) if part and URL_SLUG_RE.match(part) else part for part in URL_DELIMS_RE.split(url))
ugeturl_lazy = lazy(ugeturl, six.text_type)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment