本文將對django2.0新出的path函數的語法和使用進行介紹,雖然目前還是可以使用django.conf.urls里的函數,但是你還是要熟悉一下新的語法,以方便進行后續的開發工作。
path函數定義
path(route, view, kwargs=None, name=None)
例子
from django.urls import include, path urlpatterns = [ path('index/', views.index, name='main-view'), path('bio/<username>/', views.bio, name='bio'), path('articles/<slug:title>/', views.article, name='article-detail'), path('articles/<slug:title>/<int:section>/', views.section, name='article-section'), path('weblog/', include('blog.urls')), ... ]
route中可用自動類型轉換
str - 匹配字符串(不寫的話默認此類型) 不含最后的斜線
int - 整數
slug - 匹配ASCII字母和數字,含下划線和減號
uuid - 匹配UUID 返回一個UUID實力對象(UUID中的字母全部為小寫)
path - 匹配所有不為空的路徑,含最后的斜線
另外在django.urls新增了re_path來匹配正則,用法和老的url一致。
使用path前
re_path(r'^user/(?P<pk>\d+)/$', ProfileDetailView.as_view()), re_path(r'^user/(?P<year>[0-9]{4})/$', YearArchive.as_view()),
使用path后
path('user/<int:pk>/', ProfileDetailView.as_view()), path('user/<int:year>/', YearArchive.as_view()), #無4位數限制