How to make Django create slug from unicode characters?

醉酒当歌 提交于 2019-11-30 07:27:25
e-satis

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/сайн-уу

Presuming you want to automatically create a slug based on your NewsModel's title, you want to use slugify:

from django.template.defaultfilters import slugify

def save(self,*args, **kwargs):
  if self.slug is None:
    self.slug = slugify(self.title)
  super(NewsModel, self).save(*args, **kwargs)

This is what i am using in my projects. i know this question is for many times ago but i hope my solution help someone. i should mention that there is a good solution for this in https://github.com/mozilla/unicode-slugify but this is what i use:

import re
import unicodedata

try:
    from django.utils.encoding import smart_unicode as smart_text
except ImportError:
    from django.utils.encoding import smart_text

def slugify(value):
    #underscore, tilde and hyphen are alowed in slugs
    value = unicodedata.normalize('NFKC', smart_text(value))
    prog = re.compile(r'[^~\w\s-]', flags=re.UNICODE)
    value = prog.sub('', value).strip().lower()
    return re.sub(r'[-\s]+', '-', value)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!