patternpythondjangoCriticalCanonical
What is a "slug" in Django?
Viewed 0 times
slugwhatdjango
Problem
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 below in this glossary:
Slug
A short label for something, containing only letters, numbers,
underscores or hyphens. They’re generally used in URLs. For example,
in a typical blog entry URL:
https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit
(spring) is the slug.
I have read its definition below in this glossary:
Slug
A short label for something, containing only letters, numbers,
underscores or hyphens. They’re generally used in URLs. For example,
in a typical blog entry URL:
https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit
(spring) is the slug.
Solution
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:
Now let's pretend that we have a Django model such as:
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:
Or, you might want to reference the title like this:
Since spaces aren't valid in URLs, they must be replaced by
Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:
In this example,
Also see the URL of this very web page for another example.
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/23Or, you might want to reference the title like this:
www.example.com/article/The 46 Year Old VirginSince spaces aren't valid in URLs, they must be replaced by
%20, which results in:www.example.com/article/The%2046%20Year%20Old%20VirginBoth attempts are not resulting in very meaningful, easy-to-read URL. This is better:
www.example.com/article/the-46-year-old-virginIn 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.
Code Snippets
www.example.com/article/23www.example.com/article/The 46 Year Old Virginwww.example.com/article/The%2046%20Year%20Old%20Virginwww.example.com/article/the-46-year-old-virginContext
Stack Overflow Q#427102, score: 962
Revisions (0)
No revisions yet.