django URL路由匹配规则(path/re_path/include)
1、path不支持正则匹配
语法:path(‘URL/‘,app01视图文件views.视图中执行的函数)
项目urls.py文件
from django.urls import path # 导入path函数 from django.urls import re_path #导入re_path函数 from django.urls import include # 导入include函数 from django.contrib import admin from app01 import views urlpatterns = [ path(‘admin/‘, admin.site.urls), #path函数 path(‘index/‘,views.index), # views视图,这条URL对应的执行函数 ]
2、re_path支持正则匹配
项目urls.py文件
from django.urls import path from django.urls import re_path from django.urls import include from django.contrib import admin from index import views urlpatterns = [ path(‘admin/‘, admin.site.urls), re_path(‘^index/‘,views.index), # 匹配以index开头的URL ]
3、include引用头文件
项目urls.py文件
from django.urls import path from django.urls import re_path from django.urls import include from django.contrib import admin from index import urls urlpatterns = [ path(‘admin/‘, admin.site.urls), re_path(‘^index/‘,include(‘index.urls‘)), # ]
app01的urls.py文件中
from django.urls import path,re_path from django.urls import include from index import views urlpatterns = [ re_path(r‘^index/$‘,views.index1), ]
注意:
1、在项目中URL总路由urls.py文件,引用include函数时,子URL路由urls.py文件,匹配URL是两个URL相加的,注意“/”
例如:
#总路由 re_path(‘^index/‘,include(‘index.urls‘)), #子路由 re_path(r‘^index/$‘,views.index1) #访问的就是这个URL:http://127.0.0.1:8000/index/index/
也可以这样写
#总路由 re_path(‘^index‘,include(‘index.urls‘)), #子路由 re_path(r‘^/index/$‘,views.index1) #访问的就是这个URL:http://127.0.0.1:8000/index/index/
但是不能这样写,明显URL发生改变了
#总路由 re_path(‘^index‘,include(‘index.urls‘)), #子路由 re_path(r‘^index/$‘,views.index1) #访问的就是这个URL:http://127.0.0.1:8000/indexindex/