1
# -*- coding: utf-8 -*-
2 4
from django.conf import settings
3 4
from django.utils.module_loading import import_string
4 4
from django.utils.text import slugify as django_slugify
5

6

7 4
def slugify(value, allow_unicode=False):
8
    """Override default slugify in django to handle custom scenarios.
9

10
    Run value through functions declared in SLUGIFY_PROCESSORS. The value is
11
    then passed-through to django's slugify.
12

13
    :param value: string to slugify
14
    :type value: string
15
    :param allow_unicode: whether or not to allow unicode (e.g. chinese)
16
    :type allow_unicode: bool
17

18
    Examples of slugify processors, assume *project/app/slugify_processors.py*:
19

20
    .. code-block:: python
21

22
        def slugify_programming_languages(value):
23
            value = value.lower()
24

25
            value = value.replace('c++', 'cpp')
26
            value = value.replace('c#', 'c-sharp')
27
            return value
28

29
        def slugify_geo_acronyms(value):
30
            value = value.lower()
31

32
            value = value.replace('New York City', 'nyc')
33
            value = value.replace('United States', 'usa')
34
            return value
35

36
        def slugify_us_currency(value):
37
            value = value.lower()
38

39
            value = value.replace('$', 'usd')
40
            value = value.replace('US$', 'usd')
41
            value = value.replace('US Dollar', 'usd')
42
            value = value.replace('U.S. Dollar', 'usd')
43
            return value
44

45
    Settings:
46

47
    .. code-block:: python
48

49
        SLUGIFY_PROCESSORS = [
50
            'project.app.slugify_programming_languages',
51
            'project.app.slugify_geo_acronyms',
52
            'project.app.slugify_us_currency',
53
        ]
54
    """
55 4
    if hasattr(settings, 'SLUGIFY_PROCESSORS'):
56 4
        for slugify_fn_str in settings.SLUGIFY_PROCESSORS:
57 4
            slugify_fn_ = import_string(slugify_fn_str)
58 4
            value = slugify_fn_(value)
59

60 4
    return django_slugify(value, allow_unicode)

Read our documentation on viewing source code .

Loading