1

I'm trying to create Unicode slugs with Django. The problem arises when it tries to save and resolve URLs with said slugs with Unicode characters in it. When I checked, Django seems to modify the characters when SlugField is used.

This is my models.py:

class Post(models.Model):
    title = models.CharField()
    slug = models.SlugField(unique=True, blank=True, allow_unicode=True)

urls.py

from django.urls import path

from . import views


app_name = 'blog'
urlpatterns = [
    # Cat
    path('', views.CatList.as_view(), name='cat-list'),
    path('create/', views.CatCreate.as_view(), name='cat-create'),
    path('<slug:cat_slug>/', views.CatDetail.as_view(), name='cat-detail'),
    path('<slug:cat_slug>/edit/', views.CatEdit.as_view(), name='cat-edit'),

    # Post
    path('<slug:cat_slug>/posts/', views.CatDetail.as_view(), name='post-list'),    
    path('<slug:cat_slug>/posts/create/', views.PostCreate.as_view(), name='post-create'),
    path('<slug:cat_slug>/posts/<slug:post_slug>/', views.PostDetail.as_view(), name='post-detail'),
    path('<slug:cat_slug>/posts/<slug:post_slug>/edit/', views.PostEdit.as_view(), name='post-edit')
]   

And I use slugify(slug, allow_unicode=True) to auto-generate slug from title.

So to test this I used தமிழ் as title. Instead of a successful redirect to the URL /cats/test-cat/posts/தமிழ்/ Django showed NoReverseMatch exception with the following message.

Reverse for 'post-detail' with arguments '('test-cat', 'zw93tz-தமழ')' not found. 1 pattern(s) tried: ['cats/(?P<cat_slug>[-a-zA-Z0-9_]+)/posts/(?P<post_slug>[-a-zA-Z0-9_]+)/$']

When I check the database, the title field has the right characters தமிழ் but the slug field has the modified characters தமழ.

When I looked up for solutions, I found a workaround to use <str> instead of <slug> in urls.py.

Why is this happening with <slug> and how to fix this?

Ken
  • 859
  • 2
  • 14
  • 33

0 Answers0