Alireza Ghaffari
Alireza Ghaffari

Reputation: 1104

Slugify and an issue with Persian language

I have model like following:

class Rule(models.Model):
    business = models.ForeignKey('profiles.Employee', limit_choices_to={'is_employee': True})
    title = models.CharField(max_length=50, blank=False)
    slug = models.SlugField(max_length=50, blank=True, null=True)
    detail = models.TextField(max_length=200)
    frequency = models.CharField(choices=freqs, max_length=10, blank=True, null=True)
    update = models.DateTimeField(auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{}--{}".format(self.business, self.title)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if not self.title == "":
            self.slug = slugify(self.title)
        super(Rule, self).save()

I don't have any problem with saving English value records in slug but when I wanna save Persian strings I'm encountered with blank field, although I wrote ALLOW_UNICODE_SLUGS = True in the settings.py file. What should I do?

Upvotes: 0

Views: 918

Answers (2)

Mojtaba Yousefi
Mojtaba Yousefi

Reputation: 676

The new option which is being introduced in django version 1.9 is SlugField.allow_unicode

If True, the field accepts Unicode letters in addition to ASCII letters. Defaults to False. doc

For example:

In models.py file, define the slug column like below:

slug = models.SlugField(allow_unicode=True)

Upvotes: 4

Alireza Ghaffari
Alireza Ghaffari

Reputation: 1104

It worked! First of all you should install unidecode by Pip:

pip install unidecode

Or use the following link: https://pypi.python.org/pypi/Unidecode

After that:

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    from unidecode import unidecode
    from django.template import defaultfilters
    if not self.title == "":
        self.slug = defaultfilters.slugify(unidecode(self.title))
    super(rule, self).save()

It is not pretty good for Persian(Arabic) language but it works!

Upvotes: 1

Related Questions