HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythondjangoCritical

What is a "slug" in Django?

Submitted by: @import:stackoverflow-api··
0
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.

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:

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.

Code Snippets

www.example.com/article/23
www.example.com/article/The 46 Year Old Virgin
www.example.com/article/The%2046%20Year%20Old%20Virgin
www.example.com/article/the-46-year-old-virgin

Context

Stack Overflow Q#427102, score: 962

Revisions (0)

No revisions yet.