"Slug" is a newspaper-industry term, and since Django has its roots
there, it's now a Django term.
Django does' in fact, contain a slugify function:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#slugify
You can import and use this in a view, not just in a template: from
django.template.defaultfilters import slugify
Note that it does not enforce uniqueness; you'd have to do that
yourself. We just append a number to the slug.
So, for example, if you already had john_smith as a slug, you'd end up
with john_smith2.
We use unique slugs, and store them in the database. The main reason
(I think) for storing it in the
database is the fact that you can easily retrieve a model instance
using (slug = value) in the objects.get().
Having the ID and the slug both passed in the URL is redundant. We use
one or the other. Your use case may
dictate a different approach, but it doesn't make sense to me to have
two values in the URL, both of which should
be referring to the exact same record.
Shawn
I'm looking into adding prettier URLs into my site with the help of
slugs. I've never done something like this before, so I'm doing a lot
of reading and am having trouble "getting" slugs. When creating URLs,
couldn't you just do do something like "example.com/45/slug-goes-
here"? Then have the view only use the 45 (the ID) to look up the blog
entry (or whatever). Then it checks to see if the slug matches, if it
does then carry on, if not, issue a redirect with the correct slug. It
seems like to me this is the easiest way to go about this, but in my
google searches, this is Not The Right Way (TM). It seems that the way
you're supposed to do it involves a seperate slug field that gets
stored in the database. What is the point of this? I'm about to
implement this the way I described above. Is there anything I'm
missing?
Also, is there some kind of "slugify" function build into django? I
know theres the slugify template tag, but what about something not in
that I can use in my models and views?
Yes you could.
> It seems that the way
> you're supposed to do it involves a seperate slug field that gets
> stored in the database. What is the point of this? I'm about to
> implement this the way I described above. Is there anything I'm
> missing?
Well I usually set the slug field as the pk (which removes the `id`
field Django automatically adds to the table). That way I get
`example.com/slug-goes-here` and the view only uses the slug to look
up the item, not an artificial ID (naturally one can also consider the
slug to be artificial: since it's a transformation on the name/title
of the item/entry, one could use the name/title as a PK, though I
don't think even Django 1.1's extensions to the ORM handle that kind
of cases gracefully).