doraemon的python django框架的路由详解(国庆大更新)

doraemon548542 2021-05-07

栏目: 技巧 ·

来源: doraemon548542

作者:doraemon548542

简介  这篇文章主要介绍了doraemon的python django框架的路由详解(国庆大更新)以及相关的经验技巧,文章约11528字,浏览量840,点赞数5,值得参考!

### 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   按照位置传参
  - {% urlblogs 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
```

 


以上就是本文的全部内容,希望对大家的学习有所帮助,本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 原文地址:https://www.cnblogs.com/doraemon548542/p/11638544.html

相关文章

doraemon的python 守护进程和Process

doraemon的python csrf校验(国庆大更新)

doraemon的python centos的入门

doraemon的python ORM必会操作(国庆大更新)

doraemon的python centos的入门(二)文件目录操作

doraemon的python MongoDB的基础 增删改查和$用法

doraemon的python 爬虫 http和https的区别

doraemon的python centos的入门(五)用户和用户组权限