What is a "slug" in Django?
Asked Answered
R

14

766

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.

Rossy answered 9/1, 2009 at 4:52 Comment(1)
For instant understanding look at the URL of the site you're in: https://stackoverflow.com/questions/{id}/{slug}Cobber
T
956

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:

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

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.

Tagliatelle answered 9/1, 2009 at 5:31 Comment(11)
Good description, but to add: SlugField doesn't ensure uniqueness out of the box, so if using it by default, this is a better URL: www.example.com/article/the-40-year-old-virgin/23/ Where '23' is the article.id, and is what's actually used to do the query (also faster than querying on the slug).Lusk
I find www.example.com/article/23/the-40-year-old-virgin easier to read.Seniority
If you serve content based on the id, decide whether to check that the slug matches the content (and return 404 if it doesn't) or ignore it completely. I don't think there's a general rule for what's best, SEO-wise. SO will still display this page if you enter #427602 in your browser.Revoice
@Daniel Just bear in mind, a slug also hides the real database ID, so your example defeats one advantage of using a slug.Coblenz
@Coblenz there really should be no need to hide database IDs - assume all your URLs are publicly known anyway.Tagliatelle
@Josh Yeah /article/4358639485639 is so much more SEO-friendly than article/title.html.Coblenz
@Coblenz the slug is added for SEO and for permalink nicey-ness. The ID is used for indexed lookup. The SEO for stackoverflow is brilliant - and they use exactly this strategy. Your argument was "hide the database id", which you've now turned in to "SEO". What's the go?Tagliatelle
Very nice example for defining slugLogogram
notice the url of current page, https://stackoverflow.com/questions/427102/what-is-a-slug-in-django, the slug is what-is-a-slug-in-djangoProgressist
@JoshSmeaton because database IDs are an internal representation and can quite reasonably change over time. Migrating from ints to UUIDs, namespacing them, migrating from one database to another... None of those things should cause URLs people may have bookmarked to change.Agglutinogen
I find using AutoSlugField in django extensions the best for generating slugs in most of the use cases.Dubenko
G
177

If I may provide some historical context :

The term "slug" has to do with casting metal—lead, in this case—out of which the press fonts were made. Every paper then had its fonts factory regularly re-melted and recast in fresh molds, since after many prints they became worn out. Apprentices like me started their career there, and went all the way to the top (not anymore).

Typographs had to compose the text of an article in a backward manner with lead characters stacked in a wise. So at printing time the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one. Therefore the slugs, (like snails) also the slow stories (the last to be fixed) were many on the bench waiting, solely identified by their fist letters, mostly the whole title generally more readable. Some "hot" news were waiting there on the bench, for possible last minute correction, (Evening paper) before last assembly and definitive printing.

Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers. A-django-enthusiast-&-friendly-old-slug-boy-from-France.

Grigson answered 15/8, 2009 at 15:45 Comment(0)
T
80

The term 'slug' comes from the world of newspaper production.

It's an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) 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 'kate-and-william' story?".

Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william.

Even Stack Overflow itself does this, with the GEB-ish(a) self-referential https://mcmap.net/q/53980/-what-is-a-quot-slug-quot-in-django/427201#427201, although you can replace the slug with blahblah and it will still find it okay.

It may even date back earlier than that, since screenplays had "slug lines" at the start of each scene, which basically sets the background for that scene (where, when, and so on). It's very similar in that it's a precis or preamble of what follows.

On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.

Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the 'piece of metal' definition to the 'story summary' definition. From there, it's a short step from proper printing to the online world.


(a) "Godel Escher, Bach", by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, "Metamagical Themas".

Tactful answered 9/1, 2009 at 6:1 Comment(1)
dmid://uu457selfrefer1645699930Collazo
G
42

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 was generated and when you see in the address bar you will see your question title with "-" in place of the spaces. That's exactly the job of a slug field.

Enter image description here

The title entered by you was something like this -> What is a “slug” in Django?

On storing it into a slug field it becomes "what-is-a-slug-in-django" (see URL of this page)

Godson answered 12/9, 2014 at 12:32 Comment(0)
A
34

Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.

Slug can create using SlugField

Ex:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

If you want to use title as slug, django has a simple function called slugify

from django.template.defaultfilters import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)

    def slug(self):
        return slugify(self.title)

If it needs uniqueness, add unique=True in slug field.

for instance, from the previous example:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug

Amphimacer answered 31/10, 2016 at 18:14 Comment(1)
Can use Django extensions AutoSlugField, works best in most cases.Dubenko
M
31

From here.

“Slug” is a newspaper term, but what it means here is the final bit of the URL. For example, a post with the title, “A bit about Django” would become, “bit-about-django” automatically (you can, of course, change it easily if you don’t like the auto-generated slug).

Misogyny answered 9/1, 2009 at 4:56 Comment(0)
G
18

It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)

Gnosticism answered 9/1, 2009 at 5:2 Comment(0)
F
9

Also auto slug at django-admin. Added at ModelAdmin:

prepopulated_fields = {'slug': ('title', )}

As here:

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug')
    search_fields = ('content', )

    prepopulated_fields = {'slug': ('title', )}
Flynt answered 21/1, 2013 at 12:42 Comment(0)
T
8

A slug is the part of a URL which identifies a particular page on a website in an easy to read form.

For example, /building-your-1st-django-site.

Slug only Contains:

  • Letters : a-z,A-Z
  • Numbers : 0-9
  • Underscores : _
  • Hyphens : -
Thyrsus answered 13/6, 2021 at 21:18 Comment(0)
M
4

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.

Motherofpearl answered 14/8, 2018 at 7:44 Comment(0)
M
2

It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL.

Manisa answered 4/12, 2020 at 9:6 Comment(0)
O
2

Slug is used in Django to dynamically generate a human-friendly/readable URL. For example, the current URL of this page says: What is a "slug" in Django?.

Notice how the URL was slugify with the actual question(what is a slug in Django)

Overwrite answered 6/1, 2022 at 13:20 Comment(0)
H
1

In short slug help get rid of those ugly looking urls with valid-urls for examples in an ecommerec site instead of showing the url as www.myecom.com/product/5432156 i can show it like www.myecom.com/product/iphone11 with the help of slug

Heinie answered 9/11, 2020 at 10:1 Comment(0)
J
0

In addition to other answers, Google Search Central says for SEO as shown below:

Consider using hyphens to separate words in your URLs, as it helps users and search engines identify concepts in the URL more easily. We recommend that you use hyphens (-) instead of underscores (_) in your URLs.

So, you should use - to separate the words of slug as shown below:

http://example.com/blog/my-1st-blog
                      #   ↑   ↑ Use hyphens

Instead of _ as shown below:

http://example.com/blog/my_1st_blog
                      #   ↑   ↑ Don't use underscores

In addition, - is used to separate your question title What is a "slug" in Django? of slug as shown below:

https://mcmap.net/q/53980/-what-is-a-quot-slug-quot-in-django
                            # Hyphens are used ↑  ↑ ↑    ↑  ↑
Jerrodjerrol answered 12/5, 2023 at 1:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.