什么是“蛞蝓"?在姜戈? [英] What is a "slug" in Django?

查看:37
本文介绍了什么是“蛞蝓"?在姜戈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读 Django 代码时,我经常在模型中看到所谓的slug".我不太确定这是什么,但我知道它与 URL 有关系.这个 slu-thing 应该如何以及何时使用?

When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?

(我在本词汇表中阅读了它的定义.)

(I have read its definition in this glossary.)

推荐答案

slug"是一种生成有效 URL 的方法,通常使用已经获得的数据.例如,slug 使用文章的标题来生成 URL.我建议通过给定标题(或其他数据)的函数生成 slug,而不是手动设置.

A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

示例:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

现在让我们假设我们有一个 Django 模型,例如:

Now let's pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

您将如何使用 URL 和有意义的名称引用此对象?例如,您可以使用 Article.id 使 URL 如下所示:

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

www.example.com/article/23

或者,您可能想像这样引用标题:

Or, you might want to reference the title like this:

www.example.com/article/The 46 Year Old Virgin

由于空格在 URL 中无效,因此必须将它们替换为 %20,从而导致:

Since spaces aren't valid in URLs, they must be replaced by %20, which results in:

www.example.com/article/The%2046%20Year%20Old%20Virgin

这两种尝试都没有产生非常有意义、易于阅读的 URL.这样更好:

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

www.example.com/article/the-46-year-old-virgin

在此示例中,the-46-year-old-virgin 是一个 slug:它是通过将所有字母向下大写并用连字符替换空格从标题创建的 -.

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

另请参阅此网页的 URL 以获取另一个示例.

Also see the URL of this very web page for another example.

这篇关于什么是“蛞蝓"?在姜戈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆