`include()`:包含其他 URLconf 模块。
用法
----
- include 一个模块
- include 一个变量
~~~
# in URLconf 包含一个模块
from django.urls import include, path
urlpatterns = [
# ... snip ...
path('community/', include('aggregator.urls')),
path('contact/', include('contact.urls')),
# ... snip ...
]
~~~
~~~
# in URLconf 包含一个变量
from django.urls import include, path
from apps.main import views as main_views
from credit import views as credit_views
extra_patterns = [
path('reports/', credit_views.report),
path('charge/', credit_views.charge),
]
urlpatterns = [
path('credit/', include(extra_patterns)),
]
~~~
#### 第二种方式可以用来去除 URLconf 中的冗余。如:
~~~
# in URLconf
from django.urls import path
from . import views
urlpatterns = [
path('<page_slug>-<page_id>/history/', views.history),
path('<page_slug>-<page_id>/edit/', views.edit),
path('<page_slug>-<page_id>/discuss/', views.discuss),
path('<page_slug>-<page_id>/permissions/', views.permissions),
]
~~~
去除冗余:
~~~
# in URLconf
from django.urls import include, path
from . import views
urlpatterns = [
path('<page_slug>-<page_id>/', include([
path('history/', views.history),
path('edit/', views.edit),
path('discuss/', views.discuss),
path('permissions/', views.permissions),
])),
]
~~~
include 参数传递
---------
子 URLconf 会收到父 URLconf 捕获的所有参数。
如,以下示例中捕获的 `<username>` 会被正确传递:
~~~
# In settings/urls/main.py
from django.urls import include, path
urlpatterns = [
path('<username>/blog/', include('foo.urls.blog')),
]
# In foo/urls/blog.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog.index),
path('archive/', views.blog.archive),
]
~~~
- 开始
- 安装 django
- 配置语言、时区
- 创建项目
- 执行项目
- Applications
- 应用
- 配置应用
- INSTALLED_APPS
- django apps 包
- AppConfig 子类
- 应用的复用
- 路由
- URLconf
- path
- 转换器
- re_path
- 捕获参数
- URL 反向解析
- include
- 额外参数
- URL 命名空间
- Settings
- Core Settings
- INSTALLED_APPS
- django API
- apps
- config.py -- AppConfig 类
- registry.py -- Apps 类
- db
- models.fields 包
- 字段类型
- 字段选项
- null、blank
- 模型
- 简介
- 字段
