Django URL 反向通配符?
Django URL wildcard with reverse?
在docs里面说URL是从上到下测试的:
/articles/2003/ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here, Django would call the function views.special_case_2003(request)
但根据我的经验,这并没有发生 - 我希望最后一个 URL 是一个通配符,以匹配任何其他规则未捕获的内容,但这条规则最终会捕获所有内容。我试过把它放在顶部,然后放在底部。
要求如下:
- 任何未被其他规则捕获的内容都应匹配 home
。
- home
的反向应该匹配最短的接受 URL,在这种情况下它将是空白的。
如何实现?
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('project.api')),
url(r'^', include('places.urls')),
]
places.urls
:
app_name = 'places'
urlpatterns = [
url(r'^([0-9]+)/$', TemplateView.as_view(template_name=app_name + '/detail.html'), name='detail'),
url(r'^', TemplateView.as_view(template_name=app_name + '/home.html'), name='home'), # Single page app
]
一种方法是捕获所有其他 url 并重定向到主页的 url,这将使主页的 urlconf 保持一致。代码如下所示,但如果您希望任何其他 url 不经过重定向直接返回主页,只需更改下面 urlpatterns
中最后一个 url
引用的视图即可。
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('project.api')),
url(r'^', include('places.urls')),
# catch all other urls
url(r'^.*/$', views.redirect_to_home,name='redirect-to-home'),
]
views.py
from django.shortcuts import redirect
from django.core.urlresolvers import reverse_lazy
def redirect_to_home(request):
# assuming home has an urlconf name of 'home'
return redirect(reverse_lazy('home'))
在docs里面说URL是从上到下测试的:
/articles/2003/ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here, Django would call the function views.special_case_2003(request)
但根据我的经验,这并没有发生 - 我希望最后一个 URL 是一个通配符,以匹配任何其他规则未捕获的内容,但这条规则最终会捕获所有内容。我试过把它放在顶部,然后放在底部。
要求如下:
- 任何未被其他规则捕获的内容都应匹配 home
。
- home
的反向应该匹配最短的接受 URL,在这种情况下它将是空白的。
如何实现?
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('project.api')),
url(r'^', include('places.urls')),
]
places.urls
:
app_name = 'places'
urlpatterns = [
url(r'^([0-9]+)/$', TemplateView.as_view(template_name=app_name + '/detail.html'), name='detail'),
url(r'^', TemplateView.as_view(template_name=app_name + '/home.html'), name='home'), # Single page app
]
一种方法是捕获所有其他 url 并重定向到主页的 url,这将使主页的 urlconf 保持一致。代码如下所示,但如果您希望任何其他 url 不经过重定向直接返回主页,只需更改下面 urlpatterns
中最后一个 url
引用的视图即可。
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('project.api')),
url(r'^', include('places.urls')),
# catch all other urls
url(r'^.*/$', views.redirect_to_home,name='redirect-to-home'),
]
views.py
from django.shortcuts import redirect
from django.core.urlresolvers import reverse_lazy
def redirect_to_home(request):
# assuming home has an urlconf name of 'home'
return redirect(reverse_lazy('home'))