【问题标题】:Django slug url in perisan 404perisan 404中的Django slug url
【发布时间】:2019-08-06 02:31:48
【问题描述】:

我有一个 django 网址:

path('question/<slug:question_slug>/add_vote/', views.AddVoteQuestionView.as_view())

它适用于英语蛞蝓,但当蛞蝓是波斯语时:

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

【问题讨论】:

    标签: python django django-urls slug


    【解决方案1】:

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

    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_]。

    【讨论】:

      【解决方案2】:

      这是对Selcuk的补充回答given here


      要传递这样的语言/unicode字符,你必须

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

      1 。自定义路径转换器

      如果我们查看 Django 的源代码,slug 路径转换器使用这个正则表达式,
      [-a-zA-Z0-9_]+ 在这里效率低下(参见 Selcuk 的回答)。
      因此,编写您自己的自定义 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。使用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()),
          ...
      ]
      

      【讨论】:

        猜你喜欢
        • 2018-07-06
        • 2021-10-08
        • 2021-06-29
        • 2019-04-04
        • 2014-11-06
        • 2018-11-28
        • 2013-02-11
        • 2015-02-14
        • 2012-12-02
        相关资源
        最近更新 更多