perisan 404 中的 Django slug url

Django slug url in perisan 404

我有一个 django url:

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())

根据 Django 2.1 documentation,您只能将 ASCII 字母或数字用于 slug 模式:

slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.

而正则表达式 \w 模式也匹配 Unicode 单词字符:

https://docs.python.org/3/library/re.html#index-32

For Unicode (str) patterns: Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.

这是对 Selcuk answer

的补充

要传递这样的 language/unicode 个字符,您必须

  1. Write some custom path converter
  2. 使用re_path() function

1。自定义路径转换器

如果我们查看 Django 的源代码,slug 路径转换器使用此正则表达式,
[-a-zA-Z0-9_]+ 这是低效的在这里(参见 Selcuk 的回答)。

因此,编写您自己的自定义 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()),
    ...
]