从Django应用中排除URL模式..可能吗?
我在我的项目中使用了一个django应用。我们就叫它 otherapp。
我需要在我的项目的url中包含otherapp的链接:
url(r'^other/', include('otherapp.urls'))
但是在 otherapp.urls 中有一个链接模式,我出于某种原因不想包含它。
这样做可以吗?
5 个回答
0
我写了这个函数,用来排除一些其他应用的链接。
def exclude_urls(urlpatterns, exclude):
if isinstance(urlpatterns, list):
for u in urlpatterns[:]:
if isinstance(u, RegexURLResolver):
exclude_urls(u, exclude)
elif u.name in exclude:
urlpatterns.remove(u)
elif isinstance(urlpatterns, RegexURLResolver):
exclude_urls(urlpatterns.url_patterns, exclude)
else: # module
exclude_urls(urlpatterns.urlpatterns, exclude)
return urlpatterns
exclude = ["foo", "bar"]
urlpatterns = patterns(
"",
url(r"", include(exclude_urls(app_urls, exclude))),
)
0
你可以试试这个:
from django.conf.urls import url
from otherapp import view
urlpatterns = [
url(r'^other/$', 'views.methodname'),
]
0
我试着用这种方法来解决这个问题:
from otherapp.urls import urlpatterns as other_app_urls
idxs = [0, 3, 4] #assuming 2nd and 3rd url you want to ignore
urlpatterns = ('',
url(r'^other/', include([other_app_urls[i] for i in idxs]),
)
4
你可以查看导入的链接,并通过任何你喜欢的方式来修改它们。
最简单的方法是检查一下 url.name
,不过你也可以通过匹配 regex
来查找,使用 url.regex
。
from otherapp.urls import urlpatterns as other_urlpatterns
url(r'^other/', include([url for url in other_urlpatterns if url.name != 'some-urlpattern']))
url(r'^other/', include([url for url in other_urlpatterns if url.regex.pattern != r'^some-pattern/$']))
15
有两种方法可以做到这一点:
A. 直接在这里列出所有你想要包含的链接。(不过这样不太符合DRY原则)
或者
B. 在这里定义你想要排除并返回404错误的链接。(这有点小技巧):例如:
urlpatterns = ('',
url('^other/url/to/exclude', django.views.defaults.page_not_found),
url(r'^other/', include('otherapp.urls')),
)