本文将对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位数限制

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-04-25
  • 2021-07-05
  • 2021-11-20
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-24
  • 2022-01-29
  • 2021-09-10
  • 2022-12-23
  • 2022-12-23
  • 2021-05-20
  • 2022-12-23
相关资源
相似解决方案