Reputation: 111
I am building a post app, which automatically creates slug from the post title. If there is any foreign language in title, slug is not getting generated.
I have already gone through some of the answers here, but it's not helping much. Am I missing something in below ?
class Post(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True, allow_unicode=True)
content = models.TextField()
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
Added below in settings.py
:
ALLOW_UNICODE_SLUGS = True
Upvotes: 2
Views: 993
Reputation: 12548
You need to tell slugify
that it should allow unicode, too. See docs.
def create_slug(instance, new_slug=None):
slug = slugify(instance.title, allow_unicode=True)
Also, be careful: the default max_length
for SlugField
is 50 characters. So converting a long title may result in a slug that is too long for your SlugField
and raise an exception.
Upvotes: 1