Django not matching unicode in url

廉价感情. 提交于 2020-08-22 16:52:16

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/50321644/django-not-matching-unicode-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!