views:

145

answers:

3

I'm creating a video site. I want my direct urls to a video to look like example.com/watch/this-is-a-slug-1 where 1 is the video id. I don't want the slug to matter though. example.com/watch/this-is-another-slug-1 should point to the same page. On SO, /questions/id is the only part of the url that matters. How can I do that?

+6  A: 

Stack Overflow uses the form

example.com/watch/1/this-is-a-slug

which is easier to handle. You're opening a can of worms if you want the ID to be at the end of the slug token, since then it'll (for example) restrict what kinds of slugs you can use, or just make it harder on yourself.

You can use a url handler like:

(r'^watch/(?P<id>\d+)/', 'watch')

to grab only the ID and ignore anything after the ID. (Note there's no $ end-of-line character.)

Jesse Beder
Hmm, thank you for that advice. Would it be difficult to get the id if it were example.com/watch/1-this-is-a-slug? Also, if these questions seem dumb, I'm sorry! This is the first site that I'm actually developing instead of just designing and laying out. So thanks for your help.
Matt
@Matt, it wouldn't be that difficult, but why do you want to? It's pretty standard practice to do what Stack Overflow does.
Jesse Beder
Honestly not sure why I'd want to do that. If /id/slug is acceptable, I'll do that. Thanks again.
Matt
A: 

With all due respect to Stackoverflow, this is the wrong way to do it. You shouldn't need to have two elements in the URL that identify the page. The ID is irrelevant - it's junk. You should be able to uniquely identify a page from the slug alone.

Daniel Roseman
What about duplicate titles? Or the fact that characters just get removed from the slug? Questions titled "Pointers in C++" and "Pointers in C" would both get the same slug, and it'd be impossible to create a question with an existing title, or the old question would become inaccessible. The ID is the unique identifier, and the slug is for human/search engine/etc friendliness.
Carson Myers
A: 

I haven't used Django but I've used MVC frameworks before. Generally they have some sort of URL routing feature that lets you define a pattern (usually a regular expression) which gets mapped to a controller.

This might be a good place to start: http://docs.djangoproject.com/en/dev/topics/http/urls/

As Jesse Beder stated, you would just need the regular expression to match the first URL segment (/watch) and a numerical ID, and then forward that to a watch controller, which would deal with the ID and ignore the slug.

Carson Myers