Understanding Django's "Slug"
When exploring Django code, you may encounter the term "slug." This refers to a short label used for URL creation. A slug is composed of letters, numbers, underscores, or hyphens and plays a significant role in generating meaningful and easily readable URLs.
A slug is typically derived from another piece of data, such as an article's title. Rather than manually assigning a slug, it's recommended to use a function to generate it based on the title. For example:
The 46 Year Old Virgin A silly comedy movie the-46-year-old-virgin
Consider a Django model like this:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
To reference an article using a URL with a meaningful name, you could use the slug. If you were to use the article's ID instead, the URL would be:
www.example.com/article/23
Alternatively, using the title directly would result in:
www.example.com/article/The 46 Year Old Virgin
However, spaces are not valid in URLs and would need to be replaced with , resulting in:
www.example.com/article/The 46 Year Old Virgin
Neither of these attempts creates a user-friendly URL. The slug approach is preferred:
www.example.com/article/the-46-year-old-virgin
In this example, the slug is created from the title by converting all letters to lowercase and replacing spaces with hyphens (-).
Slugs play a vital role in generating URLs that are both meaningful and easy to read. Consider the URL of this very web page as another example.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3