2

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
C14L
  • 12,153
  • 4
  • 39
  • 52
Ankit
  • 101
  • 5
  • Please update your question first by formatting it and then by adding the exact error message you recieve. Please also inform what is the slugify library you are using (Django's built in or a third party) – e4c5 May 09 '16 at 10:04
  • @e4c5 thanks for the suggestion ! I will make sure to follow this. – Ankit May 09 '16 at 11:52

1 Answers1

1

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.

C14L
  • 12,153
  • 4
  • 39
  • 52
  • Thanks for the solution and the information regarding default max_length of SlugField ! It's working fine. – Ankit May 09 '16 at 11:51
  • good to know it works @Ankit , you should then mark the answer as correct so that people who land on this page will know it works in the future. Besides you will get a badge and some browney points :) – e4c5 May 09 '16 at 11:57