django重点之url映射分发
在全局项目的urls.py中进行子项目的映射,然后在子项目中创建一个urls.py去处理自己项目中的请求,同时也实现了代码的解耦
添加路由分发的原则[全局urls.py中有写]
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
settigs.py
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 设置templates的路径为Django以前版本 # 'DIRS': [], # 注释掉该行,此为Django 2.0.1最新版本 # 'django.middleware.csrf.CsrfViewMiddleware', ...省略默认配置 STATIC_URL = '/static/' TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) # 原配置 # 静态资源文件 STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),) # 现添加的配置,这里是元组,注意逗号
mysite2/urls.py
from django.contrib import admin from django.urls import path from blog import views from django.conf.urls import url urlpatterns = [ path(r'static_index/', views.static_index), # 将路径名跟函数进行映射 ]
blog/urls.py
# blog/urls.py from blog import views from django.conf.urls import url urlpatterns = [ # 子路由分发 url(r'^helloBlog/', views.helloBlog), ]
views.py
from django.shortcuts import render, HttpResponse import datetime
页面显示: