问题
I have a django url:
path('question/<slug:question_slug>/add_vote/', views.AddVoteQuestionView.as_view())
It work fine with english slug but when slug is persian something like this:
/question/سوال-تست/add_vote/
django url throw 404 Not Found
, is there any solution to catch this perisan slug url?
EDIT:
I'm using django 2.1.5.
It work fine with this url:
re_path(r'question/(?P<question_slug>[\w-]+)/add_vote/$', views.AddVoteQuestionView.as_view())
回答1:
This is an addition to Selcuk answer given here
to pass such language/unicode characters you have to
- Write some custom path converter
- 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/<custom_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<question_slug>[\w-]+)/add_vote/$', views.AddVoteQuestionView.as_view()),
...
]
回答2:
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.
来源:https://stackoverflow.com/questions/55175353/django-slug-url-in-perisan-404