Commits

Jannis Leidel committed c8ee7a6

Added support for the translitcodec library.

  • Participants
  • Parent commits 23f7c92

Comments (0)

Files changed (3)

autoslug/settings.py

       # custom function, defined inline:
       AUTOSLUG_SLUGIFY_FUNCTION = lambda slug: 'can i haz %s?' % slug
 
-  Default value is 'django.template.defaultfilters.slugify' or,
-  pytils.translit's slugify function if installed.
+  Default value is 'django.template.defaultfilters.slugify', unidecode's
+  unidecode function or pytils.translit's slugify function if installed.
+
+  django-autoslug also ships a couple of slugify functions that use
+  the translitcodec_ Python library, e.g.::
+
+     # using as many characters as needed to make a natural replacement
+     AUTOSLUG_SLUGIFY_FUNCTION = 'autoslug.utils.translit_long'
+
+     # using the minimum number of characters to make a replacement
+     AUTOSLUG_SLUGIFY_FUNCTION = 'autoslug.utils.translit_short'
+
+     # only performing single character replacements
+     AUTOSLUG_SLUGIFY_FUNCTION = 'autoslug.utils.translit_one'
+
+.. _translitcodec: http://pypi.python.org/pypi/translitcodec
+
 """
 
 # use custom slugifying function if any

autoslug/utils.py

 # -*- coding: utf-8 -*-
 
 # django
+from django.core.exceptions import ImproperlyConfigured
 from django.db.models.fields import FieldDoesNotExist, DateField
 
 
             else:
                 yield field_name, value
 
+
 def crop_slug(field, slug):
     if field.max_length < len(slug):
         return slug[:field.max_length]
     return slug
+
+
+try:
+    import translitcodec
+except ImportError:
+    pass
+else:
+    import re
+    PUNCT_RE = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
+
+    def translitcodec_slugify(codec):
+        def _slugify(value, delim=u'-', encoding=''):
+            """
+            Generates an ASCII-only slug.
+
+            Borrowed from http://flask.pocoo.org/snippets/5/
+            """
+            if encoding:
+                encoder = "%s/%s" % (codec, encoding)
+            else:
+                encoder = codec
+            result = []
+            for word in PUNCT_RE.split(value.lower()):
+                word = word.encode(encoder)
+                if word:
+                    result.append(word)
+            return unicode(delim.join(result))
+        return _slugify
+
+    translit_long = translitcodec_slugify("translit/long")
+    translit_short = translitcodec_slugify("translit/short")
+    translit_one = translitcodec_slugify("translit/one")
 
     requires = ['python (>= 2.4)', 'django (>= 1.0)'],
     # in case you want to use slugify() with support for transliteration:
-    extras_require = {'cyrillic': 'pytils >= 0.2'},
-
+    extras_require = {
+        'cyrillic': 'pytils >= 0.2',
+        'translitcodec': 'translitcodec >= 0.3',
+    },
     description  = 'An automated slug field for Django.',
     long_description = readme,
     author       = 'Andy Mikhailenko',