Passing arguments to views in Django from constrained choices

送分小仙女□ 提交于 2019-12-10 10:04:48

问题


I am looking for the best way to pass either of two arguments to the views from the URL, without allowing any additional arguments.

For example, with the following URLs:

(r'^friends/requests', 'app.views.pendingFriends'),

(r'^friends/offers', 'app.views.pendingFriends'),

If it's possible to pass the URL to the views, so that pendingFriends knows which URL it was called from, that would work. However, I can't see a way to do this.

Instead, I could supply the arguments (requests or offers) in the URL, to a single Django view,

(r'^friends/(?P<type>\w+', 'app.views.pendingFriends'),

The argument will tell pendingFriends what to do. However, this leaves open the possibility of other arguments being passed to the URL (besides requests and offers.)

Ideally I'd like the URL dispatcher to stop this happening (via a 404) before the invalid arguments get passed to the views. So my questions are (a) is this the best approach, (b) is there a way to constrain the arguments which are passed to the views in the URL to requests or offers?

Thanks


回答1:


Remember that you have the full power of regexes to match URLs. You simply need to write a regex that accepts only what you want:

(r'^friends/(?P<type>requests|offers)', 'app.views.pendingFriends'),

If you want to list it twice, do it like this:

(r'^friends/(?P<type>requests)', 'app.views.pendingFriends'),
(r'^friends/(?P<type>offers)', 'app.views.pendingFriends'),


来源:https://stackoverflow.com/questions/7538707/passing-arguments-to-views-in-django-from-constrained-choices

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