A
A
Alexander Ermolaev2020-05-23 22:49:07
Django
Alexander Ermolaev, 2020-05-23 22:49:07

How to use the slugify function in Django?

I don't understand how to properly use Django's slugify function
>>> from django.utils.text import slugify
>>> slugify("hello world") - I was expecting 'privet world'
'world'
>>> slugify("hello" )
'' - I expected 'privet'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-05-23
@ermolalex

Take a look at the implementation of the function:

def slugify(value, allow_unicode=False):
    """
    Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
    Remove characters that aren't alphanumerics, underscores, or hyphens.
    Convert to lowercase. Also strip leading and trailing whitespace.
    """

slugify function - convert to ASCII if allow_unicode is False, convert spaces to hyphens, remove characters that are not alphanumeric, underscores or hyphens, convert to lowercase and remove spaces at the beginning and end
Cyrillic transliteration is not included in this function
By default there for lines, the following steps are performed:
In [1]: unicodedata.normalize('NFKD', 'привет world')                                                                                                                                          
Out[1]: 'привет world'

In [2]: 'привет world'.encode('ascii', 'ignore').decode('ascii')                                                                                                                               
Out[2]: ' world'

Here actually .encode('ascii', 'ignore') discards Cyrillic characters, since they are not ascii characters
. Alternatively:
In [3]: my_string = 'привет world'.translate(
  str.maketrans(
    "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
    "abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_
    ...: Y_EUA"
))                                                                                                                                                                               

In [4]: slugify(my_string)                                                                                                                                                                     
Out[4]: 'privet-world'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question