How to make Django create slug from unicode charac

2019-02-05 05:34发布

问题:

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, } )

回答1:

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



回答2:

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)


回答3:

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)