Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically create utf8 slug in Django?

Tags:

utf-8

django

slug

I want Django to automatically create slug for this model:

class News(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    teaser = models.TextField('teaser', blank=True)
    created=models.DateTimeField(auto_now_add=True)
    pub_date=models.DateTimeField(default=datetime.datetime.now)
    categories = models.ManyToManyField(Category, blank=True)
    likes = models.IntegerField(default=0)
    visits = models.IntegerField(default=0)
    slug = models.CharField(max_length=100, unique=True) 

    def __unicode__(self):
        return unicode(self.title)

    def save(self, *args, **kwargs):
        self.title = slugify_unicode(self.title)
        super(News, self).save(*args, **kwargs)

I used CharField instead of slugfield because Slug fields can only contain ASCII letters, numbers, dashses and underlines but I want to create slugs based on Persian titles.

my views.py has this function to create news items:

@staff_member_required
def add_news(request):
    if request.method == 'POST':
        form = NewsForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/all_news')

    if request.method == 'GET':
        form = NewsForm()
        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render_to_response('news/add_news.html', args)  

This works fine when I create Persian slugs manually but this is really cumbersome. so I am wondering if there is a way to make Django to create the slug based on the title at save time.

so for example, when the title is:

'یک خبر مهم'

I want to automatically create 'یک-خبر-مهم' as the slug.

like image 561
qliq Avatar asked Mar 21 '23 17:03

qliq


2 Answers

The new option which is being introduced in django version 1.9 is SlugField.allow_unicode

If True, the field accepts Unicode letters in addition to ASCII letters. Defaults to False. doc

For example:

In models.py file, define the slug column like below:

slug = models.SlugField(allow_unicode=True)
like image 133
Mojtaba Yousefi Avatar answered Mar 31 '23 18:03

Mojtaba Yousefi


Slugs need to be ASCII, so they can be safely used in URLs.

Please have a look at django-autoslug.

It will try to transliterate the title for you.

>>> import unidecode
>>> unidecode.unidecode(u'و')
'w'
>>> unidecode.unidecode(u'風')
'Feng '
like image 35
Krzysztof Szularz Avatar answered Mar 31 '23 17:03

Krzysztof Szularz