Beispiel #1
0
def slugify(value, length):
    """Take the given string and slugify it, making sure it does not exceed
    the specified length.
    """
    if len(value) > length:
        return django_slugify(value[:length/2] + value[-length/2:])
    else:
        return django_slugify(value)
Beispiel #2
0
def slugify(value):
    value = django_slugify(value)
    value = value.replace("_", "-")
    value = re.sub("[^a-zA-Z0-9]+", "-", value.strip())
    value = re.sub("\-+", "-", value)
    value = re.sub("\-$", "", value)
    return value
Beispiel #3
0
def slugify(value):
    value = django_slugify(value)
    value = value.replace('_', '-')
    value = re.sub('[^a-zA-Z0-9]+', '-', value.strip())
    value = re.sub('\-+', '-', value)
    value = re.sub('\-$', '', value)
    return value
Beispiel #4
0
def default_slugifier(value):
    """
    Oscar's default slugifier function.
    Uses Django's slugify function, but first applies unidecode() to convert
    non-ASCII strings to ASCII equivalents where possible.
    """
    return django_slugify(value)
Beispiel #5
0
def slugify(s):
    """
    Translates unicode into closest possible ascii chars before
    slugifying.
    """
#    return django_slugify(unidecode(unicode(s)))
    return django_slugify(s)
Beispiel #6
0
def slugify(text):
    """
    Converts to lowercase, removes non-word characters (alphanumerics and
    underscores) and converts spaces to hyphens. Also strips leading and
    trailing whitespace.
    """
    return django_slugify(text)
Beispiel #7
0
def slugify(value):
    if hasattr(value, '__unicode__'):
        value = value.__unicode__()
    if not isinstance(value, types.UnicodeType):
        value = unicode(value)
    value = value.replace(u'\u0131', 'i')
    return django_slugify(value)
Beispiel #8
0
def slugify(s):
    """
    Translates unicode into closest possible ascii chars before
    slugifying.
    """
    from future.builtins import str
    return django_slugify(unidecode(str(s)))
Beispiel #9
0
def slugify(txt, id=""):
    old_id = str(id)
    txt = txt[0:32]
    if old_id != '':
        txt = txt + "-" + old_id
    if txt == '':
        txt = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(15)])
    return django_slugify(txt.strip())
Beispiel #10
0
def slugify(s):
    """Slugify function that dumbs down but preserves non-Latin chars"""

    # unidecode complains if input is not unicode, but for our case, it
    # doesn't really matter
    if isinstance(s, str):
        s = unicode(s)
    return django_slugify(unidecode(s))
Beispiel #11
0
def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    converts spaces to hyphens, and truncates to 50 characters.
    """
    slug = django_slugify(value)
    slug = slug[:50]
    return slug.rstrip('-')
Beispiel #12
0
def slugify(string):
    """
    Slugify string

    :param string: string to slugify
    :return: slugified string
    """
    return django_slugify(string.replace('ł', 'l').replace('Ł', 'L'))
Beispiel #13
0
def slugify(value, do_slugify=True, overwrite_char_map={}):
    value = smart_text(value)

    __char_map.update(overwrite_char_map)
    value = re.sub("[^a-zA-Z0-9\\s\\-]{1}", __replace_char, value)

    if do_slugify:
        value = django_slugify(value)
    return value
Beispiel #14
0
def slugify(s):
    """
    Slugify string

    :param s: string to slugify
    :return: slugified string
    """

    return django_slugify(str(s).replace(str('ł'), 'l').replace(str('Ł'), 'L'))
Beispiel #15
0
def slugify(text):
    """
    Slugify function that supports unicode symbols
    :param text: any unicode text
    :return: slugified version of passed text
    """
    if django.VERSION[:2] < (1, 5):
        from django.template.defaultfilters import slugify as django_slugify
    else:
        from django.utils.text import slugify as django_slugify

    return django_slugify(force_text(unidecode(text)))
Beispiel #16
0
def slugify_uniquely(value, model, slugfield="slug"):
    """
    Returns a slug on a name which is unique within a model's table
    """

    suffix = 0
    potential = base = django_slugify(unidecode(value))
    if len(potential) == 0:
        potential = 'null'
    while True:
        if suffix:
            potential = "-".join([base, str(suffix)])
        if not model.objects.filter(**{slugfield: potential}).exists():
            return potential
        suffix += 1
Beispiel #17
0
def slugify_uniquely_for_queryset(value, queryset, slugfield="slug"):
    """
    Returns a slug on a name which doesn't exist in a queryset
    """

    suffix = 0
    potential = base = django_slugify(unidecode(value))
    if len(potential) == 0:
        potential = 'null'
    while True:
        if suffix:
            potential = "-".join([base, str(suffix)])
        if not queryset.filter(**{slugfield: potential}).exists():
            return potential
        suffix += 1
Beispiel #18
0
def slugify_uniquely_for_queryset(value, queryset, slugfield="slug"):
    """
    Returns a slug on a name which doesn't exist in a queryset
    """

    suffix = 0
    potential = base = django_slugify(unidecode(value))
    if len(potential) == 0:
        potential = 'null'
    while True:
        if suffix:
            potential = "-".join([base, str(suffix)])
        if not queryset.filter(**{slugfield: potential}).exists():
            return potential
        suffix += 1
Beispiel #19
0
def slugify_uniquely(value, model, slugfield="slug"):
    """
    Returns a slug on a name which is unique within a model's table
    """

    suffix = 0
    potential = base = django_slugify(unidecode(value))
    if len(potential) == 0:
        potential = 'null'
    while True:
        if suffix:
            potential = "-".join([base, str(suffix)])
        if not model.objects.filter(**{slugfield: potential}).exists():
            return potential
        suffix += 1
Beispiel #20
0
def slugify(title=None, length=60):
    u"""Smart slugify.

        >>> slugify(u'KOMITETO IŠVADA Įstatymo dėl Belgijos Karalystės, '
        ...         u'Bulgarijos Respublikos, Čekijos Respublikos, Danijos '
        ...         u'Karalystės, Vokietijos Federacinės Respublikos, Estijos '
        ...         u'Respublikos, Airijos, Graikijos Respublikos, Ispanijos '
        ...         u'Karalystės, Prancūzijos Respublikos, Italijos '
        ...         u'Respublikos, Kipro Respublikos, Latvijos Respublikos, '
        ...         u'Lietuvos Respublikos, Liuksemburgo Didžiosios'
        ...         u'Hercogystės, Vengrijos Respublikos, Maltos Respublikos, '
        ...         u'Nyderlandų Karalystės, Austrijos Respublikos, Lenkijos '
        ...         u'Respublikos, Portugalijos Respublikos, Rumunijos, '
        ...         u'Slovėnijos Respublikos, Slovakijos Respublikos, '
        ...         u'Suomijos Respublikos, Švedijos Karalystės, Jungtinės'
        ...         u'Didžiosios Britanijos ir Šiaurės Airijos Karalystės '
        ...         u'(Europos Sąjungos valstybių narių) ir Kroatijos '
        ...         u'Respublikos sutarties dėl Kroatijos Respublikos stojimo '
        ...         u'į Europos Sąjungą ratifikavimo projektui')
        u'komiteto-isvada-istatymo-del-belgijos---ratifikavimo-projektui'

        >>> slugify(u'KOMITETO IŠVADA Įstatymo dėl Belgijos Karalystės')
        u'komiteto-isvada-istatymo-del-belgijos-karalystes'

        >>> slugify(u'IŠVADA')
        u'isvada'

    """
    if not title:
        return ''

    begining_chars = length / 5
    slug = django_slugify(unidecode.unidecode(title))
    if len(slug) > length:
        words = slug.split('-')
        a, b = [], []
        while words and len('-'.join(a + b)) < length:
            if len('-'.join(a)) <= (len('-'.join(b)) + begining_chars):
                a.append(words.pop(0))
            else:
                b.insert(0, words.pop())
        if b:
            slug = '-'.join(a) + '---' + '-'.join(b)
        else:
            slug = '-'.join(a)
    return slug[:length + begining_chars]
Beispiel #21
0
def slugify(name, model):    
    tempslug = django_slugify(name)
    i = 1
    if not tempslug:
        tempslug = 'blank'
    while True:
        similar = model.objects.filter(slug__startswith=tempslug)
        if not similar:
            return tempslug
        num = 2
        for sim in similar:
            try:
                new_num = int(sim.slug.split(tempslug+'_')[1])
                num = max(num, new_num)
            except ValueError: pass
            except IndexError: pass
        return tempslug + '_' + str(num+1)
def slugify(name, model):    
    tempslug = django_slugify(name)
    i = 1
    if not tempslug:
        tempslug += '_2'
        i = 3
    while True:
        try:
            model.objects.get(slug=tempslug)
            if i == 1:
                tempslug = tempslug + '_2'
            else:
                tempslugparts = tempslug.split('_')[:-1]
                tempslug = '_'.join(tempslugparts)+'_'+str(i)
            i += 1

        except model.DoesNotExist:
            return tempslug
        except model.MultipleObjectsReturned:
            pass
def better_slugify(value, remove_stopwords=True, slugify=True, max_words=None):
    """
    Better slugify

    Enhancement of Django's own slugify function. Retains readability by replacing Umlaut characters
    with standard ascii chars, shortens length, removes stopwords

    Arguments:
        value - string - The String to slugify
        remove_stopwords - boolean - Remove frequently used words. For a list see stopwords Dict
        slugify - boolean - Call Django's slugify function afterwards?
        max_words - int - Number of words that are allowed. Longer strings will be shortened
    """

    lang = settings.LANGUAGE_CODE.lower()

    logger.debug("Slugifying '%s', language: %s" % (value, lang))

    # remove stopwords
    if remove_stopwords and lang in stopwords:
        words = value.split()
        value = " ".join([ w for w in words if w not in stopwords[lang] ])

    # reduce to max_words
    if not max_words is None:
        value = " ".join(value.split()[:max_words])
        
    # replace umlauts
    for umlaut, replacement in umlauts.iteritems():
        value = unicode(value.replace(umlaut, replacement))

    # and slugify
    if slugify:
        value = django_slugify(value)

    logger.debug("Slugified: %s" % value)        

    return value
Beispiel #24
0
def better_slugify(value, remove_stopwords=True, slugify=True, max_words=None):
    """
    Better slugify

    Enhancement of Django's own slugify function. Retains readability by replacing Umlaut characters
    with standard ascii chars, shortens length, removes stopwords

    Arguments:
        value - string - The String to slugify
        remove_stopwords - boolean - Remove frequently used words. For a list see stopwords Dict
        slugify - boolean - Call Django's slugify function afterwards?
        max_words - int - Number of words that are allowed. Longer strings will be shortened
    """

    lang = settings.LANGUAGE_CODE.lower()

    logger.debug("Slugifying '%s', language: %s" % (value, lang))

    # remove stopwords
    if remove_stopwords and lang in stopwords:
        words = value.split()
        value = " ".join([w for w in words if w not in stopwords[lang]])

    # reduce to max_words
    if not max_words is None:
        value = " ".join(value.split()[:max_words])

    # replace umlauts
    for umlaut, replacement in umlauts.iteritems():
        value = unicode(value.replace(umlaut, replacement))

    # and slugify
    if slugify:
        value = django_slugify(value)

    logger.debug("Slugified: %s" % value)

    return value
Beispiel #25
0
def slugify(s):
    """
    Overriding django slugify that allows to use russian words as well.
    """
    alphabet = {
        'а': 'a',
        'б': 'b',
        'в': 'v',
        'г': 'g',
        'д': 'd',
        'е': 'e',
        'ё': 'yo',
        'ж': 'zh',
        'з': 'z',
        'и': 'i',
        'й': 'j',
        'к': 'k',
        'л': 'l',
        'м': 'm',
        'н': 'n',
        'о': 'o',
        'п': 'p',
        'р': 'r',
        'с': 's',
        'т': 't',
        'у': 'u',
        'ф': 'f',
        'х': 'kh',
        'ц': 'ts',
        'ч': 'ch',
        'ш': 'sh',
        'щ': 'shch',
        'ы': 'i',
        'э': 'e',
        'ю': 'yu',
        'я': 'ya'
    }
    return django_slugify(''.join(alphabet.get(w, w) for w in s.lower()))
Beispiel #26
0
def slugify(value):
    """A (slightly) customised slugify function.
    """
    return django_slugify(unidecode(unicode(value)))
Beispiel #27
0
def slugify(value):
    from django.template.defaultfilters import slugify as django_slugify
    return django_slugify(value)
Beispiel #28
0
def slugify(string):
    return django_slugify(''.join(
        translit_table.get(letter, '') for letter in string.lower()))
Beispiel #29
0
def gen_slug(s):
    return django_slugify(''.join(alphabet.get(w, w)\
                          for w in s.lower()) + '-' + str(int(time())))
Beispiel #30
0
def slugify(s):
    '''
  Overriding django slugify that allows to use  cyrillic.
  '''
    return django_slugify(''.join(ALPHABET.get(w, w) for w in s.lower()))
Beispiel #31
0
def default(string):
    string = str(string)
    string = unidecode(string)
    return django_slugify(string.replace('_', ' ').strip())
Beispiel #32
0
def slugify(s):
    """
    Overriding django slugify that allows to use russian words as well.
    """
    return django_slugify(''.join(alphabet.get(w, w) for w in s.lower()))
Beispiel #33
0
def slugify(value):
    """
    Return a slug
    """
    return django_slugify(unidecode(value or ""))
Beispiel #34
0
def slugify(string):
    string = unicode(string)
    if use_unidecode:
        string = unidecode(string)
    return django_slugify(string)
Beispiel #35
0
def slugify(term):
    return django_slugify(get_translation(term))
Beispiel #36
0
def slugify(string):
    string = unicode(string)
    if use_unidecode:
        string = unidecode(string)
    return django_slugify(string.replace('_', ' '))
Beispiel #37
0
def slugify(name):
    return django_slugify("".join(ALPHABET.get(w, w) for w in name.lower()))
Beispiel #38
0
def template_slugify(value):
    value = django_slugify(value)
    value = value.replace('-', '_')
    return value
Beispiel #39
0
def slugify(s):
    """
    Translates unicode into closest possible ascii chars before
    slugifying.
    """
    return django_slugify(unidecode(unicode(s)))
Beispiel #40
0
def slugify(value):
    """
    Return a slug
    """
    return django_slugify(unidecode(value or ""))
Beispiel #41
0
def slugify(string):
    string = six.text_type(string)
    string = unidecode(string)
    return django_slugify(string.replace('_', ' ').strip())
Beispiel #42
0
 def slugify(value):
     return django_slugify(unidecode(value))
Beispiel #43
0
def slugify(value):
    return django_slugify(value).strip('_.- ').lower()
def slugify(value):
    from django.template.defaultfilters import slugify as django_slugify

    return django_slugify(value)
Beispiel #45
0
def slugify(string):
    string = unicode(string)
    string = unidecode(string)
    return django_slugify(string.replace('_', ' ').strip())
Beispiel #46
0
def slugify(string):
    string = unicode(string)
    string = unidecode(string)
    return django_slugify(string.replace('_', ' '))
Beispiel #47
0
 def slugify(fileName):
     fname, ext = fileName.rsplit('.',1)
     return django_slugify(fname) + '.' + ext
Beispiel #48
0
def slugify(x):
    from django.template.defaultfilters import slugify as django_slugify
    from unidecode import unidecode

    return django_slugify(unidecode(x))
Beispiel #49
0
 def slugify(fileName):
     fname, ext = fileName.rsplit('.', 1)
     return django_slugify(fname) + '.' + ext
Beispiel #50
0
def slugify(s):
    return django_slugify(''.join(alphabet.get(w, w) for w in s.lower()))
Beispiel #51
0
def slugify(s):
    # Возвращаем вызов slugify, где перебираем все символы в строке «s» и переводим их в латиницу
    return django_slugify(''.join(alphabet.get(w, w) for w in s.lower()))