Search code examples
djangounicodeslug

How to make Django create slug from unicode characters?


Django Unicode Slug how to ?

class NewsModel(models.Model):
    title = models.CharField(max_length = 300)
    slug = models.CharField(max_length = 300)
    content = models.TextField()
    def save(self,*args, **kwargs):
        if self.slug is None:
             self.slug = ???
        super(NewsModel, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("news_view", kwargs = {"slug" : self.slug, } )

Solution

  • Django comes with a function for that:

    In [11]: from django.template.defaultfilters import slugify
    In [13]: slugify(u'ç é YUOIYO  ___ 89098')
    Out[13]: u'c-e-yuoiyo-___-89098'
    

    But really your are better off using the prepopulated_fields parameter and a SlugField.

    EDIT:

    It seems to be a duplicate question, and the answer proposed in the other OP works quite well. First install unidecode, then:

    In [2]: import unidecode
    In [3]: unidecode.unidecode(u"Сайн уу")
    Out[3]: 'Sain uu
    

    You can pass it to slugify after.

    If you are looking for slugs of unicode caractèers, you can use mozilla/unicode-slugify

    In [1]: import slugify
    In [2]: slugify.slugify(u"Сайн уу")
    Out[3]: u'\u0441\u0430\u0439\u043d-\u0443\u0443'
    

    Result is http://example.com/news/сайн-уу