Skip to content
Advertisement

Write Persian in slug and use it in address bar in django

I use django and in my models I want to write Persian in slugfield (by using utf-8 or something else) and use the slug in address of page I write this class for model:

class Category(models.Model):
    name = models.CharField(max_length=20, unique=True)
    slug = models.SlugField(max_length=20, unique=True)
    description = models.CharField(max_length=500)
    is_active = models.BooleanField(default=False)
    meta_description = models.TextField(max_length=160, null=True, blank=True)
    meta_keywords = models.TextField(max_length=255, null=True, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

    def category_posts(self):
        return Post.objects.filter(category=self).count()

But there is nothing in slug column after save and I don’t know what to write in url to show Persian. Can you tell me what should I do?

I use django 1.9 and python 3.6.

Advertisement

Answer

The docstring for the slugify function is:

Convert to ASCII if ‘allow_unicode’ is False. Convert spaces to hyphens. Remove characters that aren’t alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace.

So you need to set the allow_unicode flag to True to preserve the Persian text.

>>> text = 'سلام عزیزم! عزیزم سلام!'
>>> slugify(text)
''
>>> slugify(text, allow_unicode=True)
'سلام-عزیزم-عزیزم-سلام'
>>> 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement