How to force Django to create bullets from Unicode characters?

Django Unicode Slug how?

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
source share
3 answers

Django has a function for this:

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

But actually you better use the prepopulated_fields and SlugField parameter .

EDIT:

This seems to be a recurring question, and the answer suggested in another OP works quite well. Install unidecode first , 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 slug south karakulera, 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 http://example.com/news/-

+6
source

Assuming you want to automatically create a pool based on the NewsModel header, 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) 
+1
source

This is what I use in my projects. I know this question many times, but I hope that my solution will help someone. I should mention that there is a good solution for this at 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) 
0
source

Source: https://habr.com/ru/post/911729/


All Articles