013-namespace 和 name

namespace 和 name

兩個路由函數:

- path(route, view, kwargs=None, name=None)
- re_path(route, view, kwargs=None, name=None)

url() 函數是 django.urls.re_path() 的別名。

urlpatterns = [
    url('index/', views.index, name='main-view'),
    path('blog/<int:year>/', views.article, name='article-detail'),
    ...
]

  • namespace 一般用在根路由中,如:
urlpatterns = [
    path('admin/', admin.site.urls),
    path('student/', include(('student.urls', 'student'), namespace='hello')),
]
  • name 一般用在 app 路由中,如:
urlpatterns = [
    # path('detail/<int:id>/', views.detail, name='detail'),
    path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'),
]
  • 兩個路由函數的 route 部分是地址欄 url 的一部分。前端頁面通過路由函數中的 namespce 和 name 參數可以調用相應的視圖,如:
<a href="{% url 'hello:detail' student.id %}">Hello World!</a>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章