Answer the question
In order to leave comments, you need to log in
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
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.
"""
In [1]: unicodedata.normalize('NFKD', 'привет world')
Out[1]: 'привет world'
In [2]: 'привет world'.encode('ascii', 'ignore').decode('ascii')
Out[2]: ' world'
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 questionAsk a Question
731 491 924 answers to any question