1. Including other URLconfs
原urls.py文件,多个app的路由系统写在一起,不方便管理
范例:
from django.conf.urls import url from django.contrib import admin from app01 import views from app02 import views as app02_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^publisher_list/$', views.PubList.as_view()), url(r'^edit_publisher/$', views.EditPub.as_view()), url(r'^book_list/$', views.BookList.as_view()), url(r'^templates/$', views.Templates.as_view()), url(r'^book/$', app02_views.book), ]
2. 使用include
使用:
2.1 注释app01的相关配置
from django.conf.urls import url from django.contrib import admin from app02 import views as app02_views urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^publisher_list/$', views.PubList.as_view()), # url(r'^edit_publisher/$', views.EditPub.as_view()), # url(r'^book_list/$', views.BookList.as_view()), # url(r'^templates/$', views.Templates.as_view()), url(r'^book/$', app02_views.book), ]
2.2 在app01目录中创建urls.py文件
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^publisher_list/$', views.PubList.as_view()), url(r'^edit_publisher/$', views.EditPub.as_view()), url(r'^book_list/$', views.BookList.as_view()), url(r'^templates/$', views.Templates.as_view()), ]
但是仅此而已还不够,启动Django项目,发现不能访问app01中的链接
2.3 导入urls模块的include方法
方法一:
from django.conf.urls import url, include from django.contrib import admin from app02 import views as app02_views urlpatterns = [ url(r'^admin/', admin.site.urls), # 这种方式不明确,不能根据程序区分 url(r'^', include('app01.urls')), url(r'^book/$', app02_views.book), ]
方法二:
from django.conf.urls import url, include from django.contrib import admin from app02 import views as app02_views urlpatterns = [ url(r'^admin/', admin.site.urls), # 这种方式可以根据不同的程序访问不同的url url(r'^app01/', include('app01.urls')), url(r'^book/$', app02_views.book), ]