nabil london
nabil london

Reputation: 521

Django not matching unicode in url

I have a problem with django 2.0, where a url that contains a unicode slug isn't matched, I searched for a solution but I didn't find one for my case, here's a simplified version of my code:

// models.py

class Level(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, allow_unicode=True)

in my urls file I have those patterns:

// urls.py

urlpatterns = [
path('', views.index, name='index'),
path('level/<slug:level_slug>', views.level, name='level')]

Now if I go, say to http://127.0.0.1:8000/game/level/deuxième I get this error:

Request Method: GET
Request URL:    http://127.0.0.1:8000/game/level/deuxi%C3%A8me

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

game/ [name='index']
game/level/<slug:level_slug> [name='level']
admin/
accounts/
The current path, game/level/deuxième, didn't match any of these.

but if I change the item's slug to deuxieme without the unicode character, it works fine, does anyone know the solution to this problem? thanks!

Upvotes: 11

Views: 2377

Answers (2)

marcanuy
marcanuy

Reputation: 23942

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()),

Explanation

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.

Upvotes: 16

M.javid
M.javid

Reputation: 6637

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

Upvotes: 0

Related Questions