Majid Rouhi
Majid Rouhi

Reputation: 88

How to decode URL with Persian slug in Django 2.0?

I have an archive view that using Persian slug like:

چینیها-خورشید-مصنوعی-هم-ساختند

with this url pattern:

urlpatterns = [
    ...

    path('archive/<str:slug>/', views.ArchiveDetailView.as_view(),

    ...
]

models.py:

class Archive(models.Model):
    ...

    slug = models.SlugField(_('Slug'), max_length=128, unique=True, allow_unicode=True)

    ...

views.py:

class ArchiveDetailView(DetailView):
    model = Archive

    def get_object(self, queryset=None):
        slug = self.kwargs.get(self.slug_url_kwarg)
        return get_object_or_404(self.model, slug=slug)

This work fine in local with Django built-in web server. But when I deploy site on my host (cPanel) return 404 error (only for Persian slug).

I think I find the problem, but I don't know how to fix it?

Problem is when slug in Persian, web server (Apache) or Django can't decode URL.

Upvotes: 0

Views: 404

Answers (1)

Sarah Ghanei
Sarah Ghanei

Reputation: 31

The best way for using Persian slug is to use regular expressions, it is better for decoding and it may solve your problem.


form django.urls import re_path
from . import views


urlpatterns = [
    re_path(r'(?P<slug>[-\w]+)/', views.detail),
]

or if you want to add more item for url dispatching you can use below example.

re_path(r'detail/(?P<slug>[-\w]+)/', views.detail)

For more detail click the following link: https://www.mongard.ir/one_part/73/django-persian-urls/

Upvotes: 1

Related Questions