Mas*_*isa 3 python django django-urls slug
我有一个 Django 网址:
path('question/<slug:question_slug>/add_vote/', views.AddVoteQuestionView.as_view())
Run Code Online (Sandbox Code Playgroud)
它适用于 english slug 但当 slug 是波斯语时,如下所示:
/question/????-???/add_vote/
django url throw 404 Not Found,有什么解决方案可以捕获这个 perisan slug url?
编辑:
我正在使用 Django 2.1.5。
使用此网址可以正常工作:
re_path(r'question/(?P<question_slug>[\w-]+)/add_vote/$', views.AddVoteQuestionView.as_view())
Run Code Online (Sandbox Code Playgroud)
要传递此类语言/Unicode 字符,您必须
如果我们查看 Django 的源代码,slug路径转换器使用这个正则表达式,
[-a-zA-Z0-9_]+这在这里效率低下(参见 Selcuk 的回答)。
因此,编写您自己的自定义 slug 转换器,如下所示
from django.urls.converters import SlugConverter
class CustomSlugConverter(SlugConverter):
regex = '[-\w]+' # new regex patternRun Code Online (Sandbox Code Playgroud)
然后注册,
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()),
...
]Run Code Online (Sandbox Code Playgroud)
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()),
...
]
Run Code Online (Sandbox Code Playgroud)