Django Unicode Slug how to ?
Django Unicode Slug怎么样?
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, } )
6
Django comes with a function for that:
Django有一个功能:
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.
但实际上你最好使用prepopulated_fields参数和SlugField。
EDIT:
It seems to be a duplicate question, and the answer proposed in the other OP works quite well. First install unidecode, then:
这似乎是一个重复的问题,其他OP中提出的答案非常有效。首先安装unidecode,然后:
In [2]: import unidecode
In [3]: unidecode.unidecode(u"Сайн уу")
Out[3]: 'Sain uu
You can pass it to slugify after.
你可以把它传递给slugify。
If you are looking for slugs of unicode caractèers, you can use mozilla/unicode-slugify
如果你正在寻找unicodecaractèers的slu ,,你可以使用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/сайн-уу
结果是http://example.com/news/сайн-уу
1
Presuming you want to automatically create a slug based on your NewsModel
's title, you want to use slugify
:
假设你想根据你的NewsModel的标题自动创建一个slug,你想使用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)
0
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:
这就是我在我的项目中使用的内容。我知道这个问题很多次,但我希望我的解决方案可以帮助别人。我应该在https://github.com/mozilla/unicode-slugify中提到一个很好的解决方案,但这是我使用的:
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)
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2012/03/27/b7099426c182e0ac25d2e723b8e327a8.html。