duplicate slug

I've got to the part where we use slugs in URLs. I was suprised/pleased by the fact that DetailView can automatically handle slugs as well as pks as its argument. (In theory could any Post attribute be used?).

As an experiment I created two posts with the same slug. Obviously the blog list page rendered okay, but when I clicked on one of the posts I got a 500 with get() returned more than one Post -- it returned 2!

The admin didn't try and stop me creating duplicate slugs, but would there be an easy way to do this? Perhaps you'd do something in the models save method?

Sorry You must be a logged in, registered user to answer a question.

Answers

You would usually check for the existence of the generated slug before saving it, yes, and then increment some sort of counter or append a ~ or something. You could also just look up the post by the pk and include the slug in the URL just for "prettiness".

And while you can use any attribute to look up the Post instance, DetailViews, by default, only look for slug and pk fields, because these are supposed to be unique.

Yeah, having them both there. You'd probably want to not call the slug chunk 'slug', though, to keep the CBV lookups from trying to use it.
kennethlove (Staff) on
Thanks. Sorry, when you mention looking up the post by the pk and including the slug in the URL just for prettiness, do you mean having both pk and slug in URL paths, e.g. `/blog/1/my-slug/`?
jollyfellow on