python – Reverse Url from slug with Persian or arabic languages in Django-ThrowExceptions

Exception or error:

hi i want to reverse url from slug
in model i have slug :

slug = models.SlugField(max_length=200, unique=True, allow_unicode=True)

and for get absolute url :

def get_absolute_url(self):
            return reverse('shop:product_list_by_category', args=[self.slug])

and in settings.urls :

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('shop.urls', namespace='shop')),
]

and in shop.urls :

app_name = 'shop'
urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('<slug:category_slug>/', views.product_list, name='product_list_by_category'),
    path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
]

and value for my slug is :

slug="گالری-شلوار"

now i get error :

Reverse for 'product_list_by_category' with arguments '('گالری-شلوار',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$']
How to solve:

For arabic letter you must open url encoder. You can do this with add this code to your settings.py file

ALLOW_UNICODE_SLUGS = True

###

To reverse anything you must first make it string by

Now we can reverse the string

x = 'Hello World!'
for i in x:
    x = x[::-1]

Leave a Reply

Your email address will not be published. Required fields are marked *