How can I make URLs in Django similar to stackoverflow? How can I make URLs in Django similar to stackoverflow? django django

How can I make URLs in Django similar to stackoverflow?


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.)


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.


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.