我正在构建一个帖子应用程序,它会自动从帖子标题创建 slug。如果标题中有任何外语,则不会生成 slug。
我已经在这里完成了一些答案,但这并没有太大帮助。我在下面遗漏了什么吗?
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)
在下面添加settings.py
:
ALLOW_UNICODE_SLUGS = True