简体   繁体   中英

django 1.9 slug field is not working for foreign language

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM