How can I make URLs in Django similar to stackoverflow?

此生再无相见时 提交于 2019-12-09 18:11:55

问题


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?


回答1:


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




回答2:


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.




回答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.



来源:https://stackoverflow.com/questions/2339436/how-can-i-make-urls-in-django-similar-to-stackoverflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!