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, } )
Adding Slugify to our project: Now we need to find a way to convert the title into a slug automatically. We want this script to be triggered every time a new instance of Post model is created. For this purpose, we will use signals. Note: Add new file util.py in the same directory where settings.py file is saved.
For creating unique slug in Django, we will be using Slugify and Django Signals. But first we will create a function for Creating a Slug using first_name and if that first_name is present in slug field, we will attach unique string to slug.
SlugField in Django is like a CharField, where you can specify max_length attribute also. If max_length is not specified, Django will use a default length of 50. It also implies setting Field.
A slug field in Django is used to store and generate valid URLs for your dynamically created web pages. Just like the way you added this question on Stack Overflow and a dynamic page was generated and when you see in the address bar you will see your question title with "-" in place of the spaces.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With