6

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?

3 Answers3

9

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
  • 33,081
  • 21
  • 109
  • 146
  • 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. –  Feb 26 '10 at 04:29
  • @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 Feb 26 '10 at 04:34
  • Honestly not sure why I'd want to do that. If /id/slug is acceptable, I'll do that. Thanks again. –  Feb 26 '10 at 04:37
  • How would I write the title if say the url should be /2/this-is-title and the user changes it to /2/this-is. Is it possible to write the full title always? – iJK Mar 09 '13 at 16:37
0

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
  • 37,678
  • 39
  • 126
  • 176
-3

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
  • 588,541
  • 66
  • 880
  • 895
  • 4
    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 Feb 26 '10 at 08:33