开发者

Passing arguments to views in Django from constrained choices

开发者 https://www.devze.com 2023-04-07 11:02 出处:网络
I am looking for the best way to pass either of two arguments to the views from the URL, without allowing any additional arguments.

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


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'),
0

精彩评论

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