Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример).
Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать?
В Django по умолчанию есть готовая функция slugify для таких случаев.
Но я её никогда не использую. Почему? Потому что её недостаточно!
Приведём пример
>>> from django.utils.text import slugify
>>> slugify('This is a Title')
'this-is-a-title'
Пока всё отлично
>>> slugify('This is a "Title!"')
'this-is-a-title'
Спец символы удалились, всё хорошо.
>>> slugify('Это заголовок статьи')
''
Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить
>>> slugify('Это заголовок статьи', allow_unicode=True)
'это-заголовок-статьи'
Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте.
Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою.
Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку:
🔸1. Исходный текст:
>>> text = 'Мой заголовок №10 😁!'
Взял специально посложней со специальными символами.
🔸2. Транслит
Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги.
from unidecode import unidecode
>>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山")
'N S (r) u P 1/4 Yue Shan'
Очень крутая библиотека, советую👍
В нашем случае получаем такое преобразование:
>>> text = unidecode(text)
>>> print(text)
'Moi zagolovok No. 10 !'
Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы.
А еще наш код уже поддерживает любой язык, будь то хинди или корейский.
🔸4. Фильтр символов
Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона.
>>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text)
>>> print(text)
'Moi_zagolovok_No_10_'
Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_".
🔸5. Slugify
Осталось удалить лишние символы по краям и сделать нижний регистр
>>> text = text.strip('_').lower()
>>> print(text)
'moi_zagolovok_no_10'
Получаем отличный slug! 😎
🌎 Полный код в виде функции.
______________
PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию.
#libs#tricks#django
Explainer from #Addis_Standard Newsroom:
As of 24 February, Addis Standard has not received any formal written notice, legally mandated opportunity to respond, or reasoned decision preceding the #Ethiopian Media Authority’s public claim, made via social media, that our online media registration was revoked.
Ethiopian media law is clear: suspension or revocation of a media license must follow a defined process, including written notice, a 14-working-day right of response, a reasoned decision, and access to appeal before the Authority’s Board of Directors.
None of these mandatory steps have been observed. Addis Standard remains fully operational and continues its public-interest journalism in good faith, while its publisher, #JAKENN Publishing PLC, pursues clarification and rectification through lawful channels. This matter goes beyond one newsroom, it concerns whether media regulation in Ethiopia is governed by law, due process, and institutional accountability.
Read the explainer: https://addisstandard.com/?p=55392
News: Publisher challenges #EMA’s revocation of Addis Standard registration, cites due process violations
#JAKENN Publishing P.L.C., the publisher of #Addis_Standard, has formally contested the decision by the #Ethiopian Media Authority (EMA) to revoke the outlet’s online media registration certificate, arguing that the move lacks legal basis and violates due process guarantees under Ethiopian law.
The response follows an announcement circulated on the Authority’s official social media channels on 24 February 2026, stating that Addis Standard’s registration had been revoked.
In a letter addressed to the EMA Board of Directors, JAKENN said a legal review found the announcement “exceeds the Authority’s procedural powers” and is incompatible with safeguards provided under Media Proclamation No. 1238/2021, as amended by Proclamation No. 1374/2025.
The publisher stressed that Addis Standard is operated by JAKENN Publishing P.L.C., a legally registered private....
Read more: https://addisstandard.com/?p=55387
News: #Ethiopian Media Authority revokes Addis Standard’s online media registration; Editor-in-Chief disputes claims
The Ethiopian Media Authority (#EMA) has announced the revocation of the online media registration certificate of #Addis_Standard, effective 24 February 2026, citing repeated violations of media ethics, national laws, and what it described as the country’s national interests.
The statement did not specify which reports or actions formed the basis of the decision.
Responding to the EMA’s announcement, Yonas Kedir, Editor-in-Chief of Addis Standard publications, rejected the Authority’s claims, saying the outlet had never received any formal notices of violations.
“The claim that Addis Standard received repeated notices is factually incorrect. At no point has the Ethiopian Media Authority formally notified Addis Standard newsroom of any prior violations or enforcement actions,” he said. He added that the publisher, #JAKENN Publishing PLC, ..…
Read more: https://addisstandard.com/?p=55383
News: #CPJ calls for release of #Addis_Standard editor seized by unidentified men
The Committee to Protect Journalists has called on #Ethiopian authorities to urgently locate and release #Million_Beyene, who was taken by unidentified individuals from the newsroom of Addis Standard in the capital.
In a statement issued on April 16, CPJ said Million was seized on Wednesday morning by a group of men in plainclothes from the outlet’s newsroom in #Addis_Abeba and taken to an undisclosed location.
#JAKENN Publishing PLC, publisher of Addis Standard, says the whereabouts of its Managing Editor, Million Beyene, remain unknown nearly 24 hours after he was taken by unidentified individuals from the newsroom.
In an update issued this morning, the publisher said concerns are growing over his safety, noting that his family is “increasingly distressed and deeply concerned.”
CPJ described the incident as alarming and urged authorities to determine those responsible
Read more: https://addisstandard.com/?p=56534