我有一个django网址:
path('question/<slug:question_slug>/add_vote/', views.AddVoteQuestionView.as_view())
它适用于英语slug但是当slug是波斯语时,这样的话:
/question/سوال-تست/add_vote/
django url throw 404 Not Found
,有没有解决方案来捕获这个perisan slug url?
编辑:
我正在使用django 2.1.5。
它可以正常使用此URL:
re_path(r'question/(?P<question_slug>[\w-]+)/add_vote/$', views.AddVoteQuestionView.as_view())
这是Selcuk回答given here的补充
传递你必须使用的语言/ unicode字符
如果我们查看Django的源代码,slug
路径转换器使用这个正则表达式,
[-a-zA-Z0-9_]+
在这里是无效的(见塞尔丘克的回答)。
所以,编写自己的定制slug转换器,如下所示
from django.urls.converters import SlugConverter
class CustomSlugConverter(SlugConverter):
regex = '[-\w]+' # new regex pattern
然后注册,
from django.urls import path, register_converter
register_converter(CustomSlugConverter, 'custom_slug')
urlpatterns = [
path('question/<custom_slug:question_slug>/add_vote/', views.AddVoteQuestionView.as_view()),
...
]
re_path()
你已经尝试过这种方法并取得了成功。无论如何,我在这里c&p :)
from django.urls import re_path
urlpatterns = [
re_path(r'question/(?P<question_slug>[\w-]+)/add_vote/$', views.AddVoteQuestionView.as_view()),
...
]
根据Django 2.1 documentation,您只能使用ASCII字母或数字来表示slug
:
slug
- 匹配由ASCII字母或数字组成的任何slug字符串,以及连字符和下划线字符。例如,building-your-1st-django-site
。
而正则表达式\w
模式也匹配Unicode字符:
https://docs.python.org/3/library/re.html#index-32
对于Unicode(str)模式:匹配Unicode字符;这包括大多数可以成为任何语言单词的一部分的字符,以及数字和下划线。如果使用ASCII标志,则仅匹配
[a-zA-Z0-9_]
。