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:
JavaScript
x
19
19
1
class Category(models.Model):
2
name = models.CharField(max_length=20, unique=True)
3
slug = models.SlugField(max_length=20, unique=True)
4
description = models.CharField(max_length=500)
5
is_active = models.BooleanField(default=False)
6
meta_description = models.TextField(max_length=160, null=True, blank=True)
7
meta_keywords = models.TextField(max_length=255, null=True, blank=True)
8
user = models.ForeignKey(settings.AUTH_USER_MODEL)
9
10
def save(self, *args, **kwargs):
11
self.slug = slugify(self.name)
12
super(Category, self).save(*args, **kwargs)
13
14
def __str__(self):
15
return self.name
16
17
def category_posts(self):
18
return Post.objects.filter(category=self).count()
19
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.
JavaScript
1
7
1
>>> text = 'سلام عزیزم! عزیزم سلام!'
2
>>> slugify(text)
3
''
4
>>> slugify(text, allow_unicode=True)
5
'سلام-عزیزم-عزیزم-سلام'
6
>>>
7