Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 781
nabil london Avatar asked Feb 05 '23 00:02

nabil london


1 Answers

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.

like image 182
marcanuy Avatar answered Feb 06 '23 14:02

marcanuy