开发者

Rails or web2py style URL routing in Django

I'm new to Django. Seems that Django requires to define one URL mapping rule for each controller/action (view/function in Django's term). What's the easiest way to implement Rails-style URL routing, or at least web2py-style URL routing?


For those who don't know what is Rails or web2py style URL routing.

  • Rails RESTful URL routing
  • web2py URL routing: http://dom开发者_StackOverflow社区ain.com/C/A maps to C controller A function automatically.


What you're trying to do goes explicitly against Django's design philosophy: "Tying URLs to Python function names is a Bad And Ugly Thing." So I think you have two easy choices and one hard one.

Easy #1: Stick with rails

Easy #2: Use django the way django is normally used: one URL rule per view.

Difficult: Write a generic URL dispatcher that uses introspection to look up view methods based on URLs. Be very careful making it secure. And share it when you're done. :)

Not saying you shouldn't do it. But if you're looking for an easy way to do this I suspect you'll be frustrated.


You can write it easily in custom way - write one view which accepts the url and parses it. then it loads module you want. Then you will have only one rule in urls.py file, which will call just one view function.

Also you can create middleware probably to solve the issue you have....

But I wouldn't recommend to do so and I think it is best to stick with the style of routing Django uses. Why? Because later then you will have to think about custom url resolvers, you will not be able to use for example {% url %} template tag (while you will not customize it also). I think it is not worth to reinvent something here... But this is only my opinion, it is you who decides :)

Have fun :)


I would recommend looking over the documentation for the Django URL dispatcher. There you should a bunch of ways to solve your problem. However if you are looking for a quick answer on a faster way to define your URL's then I would take a look at View Prefixes they cut down some of the bloat that you may be seeing.

If you are looking at REST then I would recommend taking a look at this article.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜