轉自:https://blog.51cto.com/jiajinh/2432449
補充理解:
先把官網上對應用命名空間(app_name)和實例命名空間(namespace)的解釋貼上:
app_name(應用命名空間)通常在app.urls模塊中指定,如:
app_name = "test" //應用命名空間 urlpatterns = [ path("article1/", views.test, name="url_a"), ]
namespace(實例命名空間)通常在ROOT_URLCONF模塊(根url路由模塊)中指定,如下面的:namespace="test1",namespace="test2",namespace="test3"
urlpatterns = [ //屬於app_name = "test"應用命名空間的三個實例命名空間
re_path(r"^test_u1/", include("test_app.urls", namespace="test1")),
re_path(r"^test_u2/", include("test_app.urls", namespace="test2")),
re_path(r"^test_u3/", include("test_app.urls", namespace="test3")),
]
上面的urlpatterns列表中的三個url配置有不同的namespace(實例命名空間),但他們都路由到test_app.urls,且在test_app.urls中指定了app_name="test"(應用命名空間),此時,test就代表了指向了它的三個namespace之一,至於test具體代表哪個namespace,就要看當前應用(current application)是哪個,比如:
服務器收到來自 http://localhost:8000/test_u2/article1/的請求,該url匹配列表中的第二條,此時namespace="test2"的應用就稱為當前應用(current application),這時候app_name="test"中的test就代表了這個當前應用對應的的實例命名空間,在模板標簽{% url "test:url_a" %}中的test就代表了test2,等價於{% url "test2:url_a" %},從而反向解析出來的url為:/test_u2/article1/,如果有來自http://localhost:8000/test_u1/article1/的請求,那么namespace="test1"的應用就稱為當前應用,test就代表了test1。總之,app_name可以代表許多實例命名空間,具體代表哪個,要看當前應用是哪個。
假設index.html中有模板標簽{% url "test:url_a" %},而此時有來自http://localhost:8000/app01/index/ 的請求需要訪問index.html,這個正在訪問的url不屬於上述三個namespace的任何一個,也就說是不存在當前應用,那么app_name就會默認指向urlpatterns中最后一個namespace即test3,那么index.html中的{% url "test:url_a" %}模板標簽,就等價於{% url "test3:url_a" %}。如果namespace名和app_name一樣,app_name就默認指向該namespace。