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.
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
%20, which results in:Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:
In this example,
the-46-year-old-virginis 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.