url(r'^reviews/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/$' ,
views.review_detail)
urlpatterns = [
url(r'^reviews/(?P[0-9]{4})/$' ,
views.year_archive,
{'foo': 'bar'}
),
]
# 接收参数,同时可以指定默认参数
def year_archive(request, year="xxx",foo="yyy"):
...
DEBUG = False # 关闭Debug
ALLOWED_HOSTS = ['*'] # 配置allowrd_hosts
def page_not_found(request):
return render(request,'page_error.html')
def page_error(request):
return render(request,'page_error')
def page_forbidden(request):
return render(request,'page_forbidden.html')
def bad_request(request):
return render(request,'bad_request.html')
from .views import *
urlpatterns = [...]
handler404 = page_not_found
handler500 = page_error
handler403 = page_forbidden
handler400 = bad_request
用法1: url() 引入额外的 URL 模式
from django.conf.urls import include, url
from apps.main import views as main_views
from credit import views as credit_views
extra_patterns = [
url(r'^reports/(?P[0-9]+)/$' , credit_views.report),
url(r'^charge/$', credit_views.charge),
]
urlpatterns = [
url(r'^$', main_views.homepage), # 直接调用视图函数
url(r'^help/', include('apps.help.urls')), #引入urls模块
url(r'^credit/', include(extra_patterns)), #引入其他urlpatterns
]
用法2:提取共用的路径前缀
urlpatterns = [
url(r'^(?P\w+)-(?P\w+)/history/$' ,
views.history),
url(r'^(?P\w+)-(?P\w+)/edit/$' ,
views.edit),
url(r'^(?P\w+)-(?P\w+)/discuss/$' ,
views.discuss),
url(r'^(?P\w+)-(?P\w+)/permissions/$' ,
views.permissions),
]
改为↓↓↓
urlpatterns = [
url(r'^(?P\w+)-(?P\w+)/' ,
include([
url(r'^history/$', views.history),
url(r'^edit/$', views.edit),
url(r'^discuss/$', views.discuss),
url(r'^permissions/$', views.permissions),
]) ),
]
五.反向解析 URL
URL 反转所需的工具:
示例:
在模板中
"{% url 'reviews-year-archive' 2012 %}">2012 Archive
或
"{% url 'reviews-year-archive' yearvar %}">{{
yearvar }} Archive
在python代码中
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
def redirect_to_year(request):
...
year = 2012
...
return HttpResponseRedirect(reverse('reviews-year-archive', args=(year,)))
方式一:
#把 reviews.urls 中定义的 URL 放在应用命名空间 reviews 中,放在实例命名空间 author-reviews中
url(r'^reviews/', include('reviews.urls',namespace='author-reviews',app_name='reviews')),
方式二:
from django.conf.urls import include, url
from . import views
reviews_patterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P\d+)/$' , views.DetailView.as_view(), name='detail'),]
url(r'^reviews/', include((reviews_patterns, 'reviews', 'author-reviews'))),
引入包含命名空间数据的对象。如果使用 include() 引入一组 url() 实例,那个对象中 的 URL 都添加到全局命名空间中。上述代码把指定的 URL 模式引入指定的应用和实例命名空间中。