(四)Django URLconfs

週末來整理一下做個筆記…

Django要如何知道召喚哪個view,是由URLCon模組所驅動,Djagno讓我們在urls.py作定義,變身成一個網址分配器(URL dispatcher),將網址轉成python function並輸出網頁。

Django讓url去對應view的函式步驟:

  1. 在瀏覽器輸入網址 http://127.0.0.1:8000/quiz ,Django會先到mysite/urls.py的urlpatterns最匹配。
  2. 發現urlpattern裡面參數url有quiz,然後召喚對應的views,最終網頁呈現我們要的畫面。

include()的做法

Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

1
from django.contrib import adminfrom django.urls import include, pathurlpatterns = [    path('quiz/', include('quiz.urls')),    path('admin/', admin.site.urls),]

include()讓我們填入app的urls.py做參數,當我們輸入的網址是http://127.0.0.1:8000/quiz/10 ,會先在mysite/urls.py匹配到quiz,那網址剩餘的部分,include會進一步去quiz/urls.py繼續做搜尋。