[Solved]-Django not matching unicode in url


In urls.py change path from using slug type to str.

From this:

    path('posts/<slug:slug>-<int:pk>/', views.PostDetailView.as_view()),

to this:

    path('posts/<str:slug>-<int:pk>/', views.PostDetailView.as_view()),


As suggested in comments, the slug path converter

Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.

but we want to keep those non-ascii characters, so we use str:

str – Matches any non-empty string, excluding the path separator, ‘/’. This is the default if a converter isn’t included in the expression.


Use the unidecode library, and set the slug field by results of unidecode.unidecode function, this library support many of languages and detect language automatically and then replace original characters by english characters.
For example if you want convert “Hello” word in china language to english characters, try below code:

$ pip install unidecode
$ python -c "import unidecode; print('---->', unidecode.unidecode('你好'))"
----> Ni Hao

Leave a comment