标签:war from code view span 国庆 pytho mes djang
### 11.8 路由 #### 11.8.1 urlconf ```python from django.conf.urls import url from app01 import views urlpatterns = [ url(r‘^admin/‘,admin.site.urls), #这里用到了正则 url(r‘^home‘,views.home,{},name=‘home‘), ] ``` #### 11.8.2 分组和命名分组 url上捕获的都是字符串 分组 ```python url(r‘^blog/([0-9]{4})/(\d{2})),views.blogs,name=‘blogs‘) #以括号为单位,捕获到的参数会按照位置传参传递给视图函数 ``` 命名分组 ```python url(r‘^blog/(?P<year>[0-9]{4})/(?P<month>\d{2})),views.blogs,name=‘blogs‘) #捕获的参数会按照关键字传参传递给视图函数 ``` 传递参数 ```python url(r‘^home/(?P<year>\d{4})$‘),views.home,{‘year‘:2019,name=‘home‘}) ``` #### 11.8.3 路由分发 ```python from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘,admin.site.urls), #这里用到了正则 url(r‘^app01‘,include(‘app01.urls‘,namespace=‘app01‘)), url(r‘^app02‘,include(‘app02.urls‘,namespace=‘app02‘)), ] ``` #### 11.8.4 url的命名和反向解析 静态路由 ```python url(r‘^home/$‘,views.home,name=‘home‘) ``` 反向解析: - 模板 {% url ‘blog‘ %} ------>‘app01/home/‘ - py文件 ```python from django.urls import reverse reverse(‘home‘) ---->‘app01/home/‘ ``` 分组: ```python url(r‘^blog/([0-9]{4})/(\d{2})),views.blogs,name=‘blogs‘) ``` 反向解析: - 模板 {% url ‘blog‘ ‘2019‘ ‘06‘%} ------>‘app01/blog/2019/06‘ - py文件 ```python from django.urls import reverse reverse(‘blogs‘,‘args=(‘2019‘,‘06‘)‘) ---->‘app01/blog/2019/06‘ ``` 命名分组: ```python url(r‘^blog/(?P<year>[0-9]{4})/(?P<month>\d{2})),views.blogs,name=‘blogs‘) ``` 反向解析: - 模板 - {% url ‘blog‘ ‘2019‘ ‘06‘%} ------>‘app01/blog/2019/06‘ 按照位置传参 - {% url‘blogs year=‘2019‘ month=‘06‘ %}-----> ‘app01/blog/2019/06‘ 按照关键字传参 - py文件 ```python from django.urls import reverse reverse(‘blogs‘,‘args=(‘2019‘,‘06‘)‘) ---->‘app01/blog/2019/06‘ from django.urls import reverse reverse(‘blogs‘,‘kwargs=(‘year‘=2019‘,‘month‘=‘06‘)‘) ---->‘app01/blog/2019/06‘ ``` #### 11.8.5 namespace ```python url(r‘^app01‘,include(‘app01.urls‘,namespace=‘app01‘)), ``` 应用 ```python {% url ‘app01:home‘ %} #在模板中应用,一定要加上namespace reverse(‘app01:home‘) #在py文件中应用,一定要加上namespace ```
doraemon的python django框架的路由详解(国庆大更新)
标签:war from code view span 国庆 pytho mes djang
原文地址:https://www.cnblogs.com/doraemon548542/p/11638544.html