Question

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.

Était-ce utile?

La solution 3

Simply replacing

self.title = slugify_unicode(self.title)

in def save(self... method of News with

    self.slug = slugify_unicode(self.title)

solved the problem.

Autres conseils

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)

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 '
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top