Search code examples
pythondjangodjango-urlsslug

Django slug url in perisan 404


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

Solution

  • 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/<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()),
        ...
    ]