通过有限的选择将Django中的观点转化为参考 [英] Passing arguments to views in Django from constrained choices

查看:108
本文介绍了通过有限的选择将Django中的观点转化为参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从URL传递两个参数的最佳方法,而不允许任何其他参数。

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

例如,使用以下内容URL:

For example, with the following URLs:

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

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

如果可以将URL传递给视图,以便 pendingFriends 知道哪个URL被调用,这将工作。但是,我看不到这样做。

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.

相反,我可以提供参数(请求提供)到单个Django视图

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

该参数将告诉 pendingFriends 该做什么,但这样会让其他参数传递给URL的可能性(除了请求提供。)

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

理想情况下,我希望URL调度程序停止这是在无效参数传递给视图之前发生的(通过404),所以我的问题是(a)这是最好的方法,(b)是否有一种方法来限制传递给URL中的视图的参数到请求提供

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?

谢谢

推荐答案

请记住,您有足够的正则表达式来匹配URL。只需要写一个只接受你想要的正则表达式:

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

这篇关于通过有限的选择将Django中的观点转化为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆