What is a “slug” in Django?

前端 未结 10 1781
感情败类
感情败类 2020-11-22 14:59

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 th

10条回答
  •  [愿得一人]
    2020-11-22 15:03

    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.

    An example:

     The 46 Year Old Virgin 
     A silly comedy movie 
     the-46-year-old-virgin 
    

    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)
    

    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
    

    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
    

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

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

    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 -.

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

提交回复
热议问题