Django slug url in persian 404

问题描述 投票:3回答:2

我有一个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())
python django django-urls slug
2个回答
2
投票

这是Selcuk回答given here的补充


传递你必须使用的语言/ unicode字符

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

1 . Custom path converter

如果我们查看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/&ltcustom_slug:question_slug>/add_vote/', views.AddVoteQuestionView.as_view()),
    ...
]

2. using re_path()

你已经尝试过这种方法并取得了成功。无论如何,我在这里c&p :)

from django.urls import re_path

urlpatterns = [
    re_path(r'question/(?P&ltquestion_slug>[\w-]+)/add_vote/$', views.AddVoteQuestionView.as_view()),
    ...
]

0
投票

根据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_]

© www.soinside.com 2019 - 2024. All rights reserved.