Django slug url in perisan 404

安稳与你 提交于 2019-12-06 09:44:26

This is an addition to Selcuk answer given here


to pass such language/unicode characters you have to

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

1 . Custom path converter

If we look into the source code of Django, the slug path converter uses this regex,
[-a-zA-Z0-9_]+ which is inefficent here (see Selcuk's answer).

So, Write your own custom slug converter , as below

from django.urls.converters import SlugConverter


class CustomSlugConverter(SlugConverter):
    regex = '[-\w]+' # new regex pattern

Then register it,

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

You've already tried and succeeded with this method. Anyway, I'm c&p it here :)

from django.urls import re_path

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

According to Django 2.1 documentation you can only use ASCII letters or numbers for slug patterns:

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

whereas regex \w pattern also matches Unicode word characters:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!