我有一个 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 字符,您必须
1 。自定义路径转换器
如果我们查看 Django 的源代码,slug路径转换器使用此正则表达式,
[-a-zA-Z0-9_]+ 在这里效率低下(请参阅 Selcuk 的回答)。
< br/> 因此,编写您自己的自定义 slug 转换器,如下所示
<b>from django.urls.converters import SlugConverter</b>
class CustomSlugConverter(<b>SlugConverter</b>):
<b>regex = '[-\w]+' # new regex pattern</b>
然后注册,
<b>from django.urls import path, register_converter
register_converter(CustomSlugConverter, 'custom_slug')</b>
urlpatterns = [
path('question/<b><custom_slug:question_slug></b>/add_vote/', views.AddVoteQuestionView.as_view()),
...
]
2。使用 re_path()
您已经尝试过这种方法并取得了成功。无论如何,我在这里 c&p :)
from django.urls import re_path
urlpatterns = [
re_path(r'question/<b>(?P<question_slug>[\w-]+)/</b>add_vote/$', views.AddVoteQuestionView.as_view()),
...
]
