简体   繁体   English

django 1.9 slug字段不适用于外语

[英]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 : 在以下settings.py添加:

ALLOW_UNICODE_SLUGS = True

You need to tell slugify that it should allow unicode, too. 您需要告诉slugify它也应该允许unicode。 See docs . 参见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 . 另外,请注意: SlugField的默认max_length50个字符 So converting a long title may result in a slug that is too long for your SlugField and raise an exception. 因此,转换长标题可能会导致对于SlugField来说太长了,并引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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