所以我为我的项目使用了django应用程序。 我们先说我们称之为 otherapp
在我的项目网址中包含其他网址:
url(r'^other/', include('otherapp.urls'))
但 otherapp.urls 中有一个网址模式,我不想出于某种原因而包含这些模式。
有可能吗?
答案 0 :(得分:8)
两种方式可以做到这一点:
一个。只需在此处定义您要包含的所有网址。 (但这是所以不是DRY )
或强>
B中。在此处定义您要排除并提升404 的网址。 (有点 hackish ):例如
urlpatterns = ('',
url('^other/url/to/exclude', django.views.defaults.page_not_found),
url(r'^other/', include('otherapp.urls')),
)
答案 1 :(得分:2)
您可以查看导入的网址,并通过您喜欢的任何方式进行修改。
最简单的方法是查看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/$']))
答案 2 :(得分:0)
你可以试试这个:
from django.conf.urls import url
from otherapp import view
urlpatterns = [
url(r'^other/$', 'views.methodname'),
]
答案 3 :(得分: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 :(得分: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))),
)