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 in this glossary.)
It's a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. I'd advise to generate the slug, using a function, given a title (or other 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, with a meaningful name? You could use Article.id so the URL would look like this:
Or, you could reference the title like so:
Problem is, spaces aren't valid in URLs, they need to be replaced by
%20
which is ugly, making it the following:That's not solving our meaningful URL. Wouldn't this be better:
That's a slug.
the-46-year-old-virgin
. All letters are downcased and spaces are replaced by hyphens-
. See the URL of this very webpage for an example!Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens.They’re generally used in URLs.(as in django docs)
A slug field in Django is used to store and generate valid URLs for your dynamically created web pages.
Just like the way you added this question on Stack Overflow and a dynamic page is generated and when you see in address bar you will see your question title with "-" in place of the spaces. That's exactly the job of a slug field.
The title entered by you was something like this -> What is a “slug” in Django?
&
On storing it into a slug, filed results it into what-is-a-slug-in-django (see URL of this page)
As a bit of history, the term 'slug' comes from the world of newspaper editing.
It's the informal name given to a story during the production process. As the story winds its torturous path from beat reporter through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixed those errors in the 'russia-cuts-europe-gas' story?".
Django uses it as part of the URL to locate the story, an example being
www.mysite.com/archives/russia-cuts-europe-gas
.