How can I make URLs in Django similar to stackover

2019-04-08 01:01发布

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条回答
男人必须洒脱
2楼-- · 2019-04-08 01:40

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

查看更多
虎瘦雄心在
3楼-- · 2019-04-08 01:55

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.

查看更多
做自己的国王
4楼-- · 2019-04-08 02:01

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.

查看更多
登录 后发表回答