Django-url 路由控制(配置,分组,分发,反向),路由名称空间
路由作用
Django 所支撑网站的目录,告诉Django,对于客户端发来的某个URL调用哪一段逻辑代码对应执行
from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^book/', views.book), # 这个路由对应着视图函数里的book方法,浏览器输入链接,就会响应到book这个函数来执行
]
简单路由配置
from app01 import views urlpatterns = [ # url( 正则表达式,views视图函数,参数,别名 ) url(r'^book/', views.book,{"id":1,"name":'lxx'},name='name'), ] # view函数: def book(request, *args, **kwargs): print(kwargs) return HttpResponse('book')
无名分组
分组之后,会把分组出来的数据,当位置参数,传到视图函数,所以,视图函数需要定义形参
# 路由层
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^book/([0-9]{4})/([0-9]{2})/', views.book,), # 无名直接用小括号分组 ]
# views视图层 def book(request,*args): print(args) # 打印结果('1221', '34')
return HttpResponse('book')
有名分组
有名分组之后,会把分组出来的数据,当关键字参数,传到视图函数
# 路由层
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^book/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.book,), # 分了两个组,year,month,视图层只能用这两个形参来接受 ]
# 视图层 def book(request,**kwargs): print(kwargs) # 打印结果:{'year': '1221', 'month': '34'}
return HttpResponse('book')
路由分发
总路由:
from django.conf.urls import url,include from django.contrib import admin
from app01 import urls as app01url # 为分支路由取别名 from app02 import urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^app01/',include(app01url)), # 分发到app01的路由 url(r'^app02/', include(urls)), # 分发到app02的路由 ]
app01文件里——分支路由
from django.conf.urls import url # 从总路由引入分支路由
from app01 import views urlpatterns = [ url(r'^book/', views.book,), ]
app02文件里——分支路由
from django.conf.urls import url # 从总路由引入分支路由 from app02 import views urlpatterns = [ url(r'^Author/', views.Author,), ]
路由反向解析跳转
路由层:
urlpatterns = [ url(r'^book/$', views.book, name='book'), url(r'^auth/([0-9]{4})/([0-9]{2})/$', views.auth, name='auth'), ]
模板层方向解析,需要指定路由名称空间
{% url "别名" 参数 参数%}
# 无参:
<a href="{% url 'auth'%}">超链接</a> # 位置参数:
<a href="{% url 'auth' 2018 12 %}">超链接</a>
# 关键字形参:
<a href="{% url 'auth' year=2018 month=12 %}">超链接</a>
视图层反向解析
# 无参:
reverse('auth') # 位置参数:
reverse('auth',1028,12)
# 关键字形参:
reverse('auth',year=1028,month=12)
from django.urls import reverse def auth(request): if request.method == 'GET':
src = reverse('test',kwargs={"xx":1234,})
src = reverse('test', xx=1234) # 跳转到test试图函数
return redirect(src)
路由名称空间:(尽量不用)
# 总路由
url(r'^blog/',include('blog.urls',namespace='blog')), # 子路由
url(r'^publish/$', views.publish,name='test'), # 注意子路由命名规范,尽量哪个app的路由标清楚,如app01_test
# 反向解析: # 视图层反向解析
url = reverse('blog:test') # 反响解析由总路由下的分支路由 # 模板层反向解析
{% url 'app01:test'%} # 反向解析有总路由下的分支路由
路由跳转
urlpatterns = [ url(r'^$', views.autherlist), # 跳到最原始页面 url(r'.*', views.error) # 路由没匹配到跳到其他页面 ]