What is a \'Slug\' in Django and why should I care?

Barbara Streisand
Release: 2024-11-04 04:28:01
Original
451 people have browsed it

What is a

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:

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

Consider a Django model like this:

<code class="python">class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)</code>
Copy after login

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
Copy after login

Alternatively, using the title directly would result in:

www.example.com/article/The 46 Year Old Virgin
Copy after login

However, spaces are not valid in URLs and would need to be replaced with , resulting in:

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

Neither of these attempts creates a user-friendly URL. The slug approach is preferred:

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

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.

The above is the detailed content of What is a \'Slug\' in Django and why should I care?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!