本文介紹了Django中url的反向查詢的方法,分享給大家,具體如下:
明確幾個概念:
1、application namespace :
正在部署的app的名稱,一個app的多個實(shí)例應(yīng)該具有相同的application namespace.
可以通過在URLconf模塊(urls.py)中設(shè)置 app_name 屬性(與urlpatterns屬性同級)來指定application namesapce.
(在django2.0版本中必須設(shè)置 app_name )
2、instance namespace :
表示app的一個特定的實(shí)例.它在當(dāng)前項(xiàng)目中應(yīng)該是唯一的.一個app可以有多個實(shí)例!
3、默認(rèn)實(shí)例(default instance of application) :
instace namesapce與所屬app的application namespace相同的實(shí)例
4、當(dāng)前實(shí)例 :
使用 reverse() 函數(shù)的 current_app 參數(shù)可以指定當(dāng)前應(yīng)用.
當(dāng)要反向解析一個namespace URL(例如'polls:index')的時候,Django將切分名稱為多個部分,然后按下面的步驟查找:

通過django文檔中的一個示例來說明,考慮polls應(yīng)用有倆個實(shí)例'publisher-polls'和'author-polls':
#urls.pyfrom django.conf.urls import include, urlurlpatterns = [ url(r'^author-polls/', include('polls.urls', namespace='author-polls')), url(r'^publisher-polls/', include('polls.urls', namespace='publisher-polls')),]from django.urls import pathfrom . import viewsapp_name = 'polls'urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), ...]根據(jù)以上設(shè)置,可以使用下面的查詢:
此時'polls:index'的namespace與當(dāng)前app的application instance(及app_name)相匹配.如果其中一個實(shí)例是當(dāng)前應(yīng)用實(shí)例(current),例如正在渲染'author-polls'的detail視圖,'polls:index'將解析到'author-polls'實(shí)例的index頁面.下面的兩種方式的結(jié)果都是'/author-polls/'
在類視圖中:
reverse('polls:index', current_app=self.request.resolver_match.namespace)在模板中: {% url 'polls:index' %}
如果沒有當(dāng)前實(shí)例(current),例如在站點(diǎn)的其它地方渲染一個頁面.'polls:index'將解析到 polls 中最后一個注冊的實(shí)例中.因?yàn)闆]有默認(rèn)實(shí)例(instance namespace為'polls'的實(shí)例),將使用 polls 注冊的最后一個實(shí)例.在這里將解析到'publisher-polls',因?yàn)樗?urlpatterns 的末尾.
如果解析'author-polls:index',將直接定位到'author-polls'的index頁面.因?yàn)榇藭r的namesapce是'author-polls',不能與application namespace匹配,根據(jù)上面的流程將直接查找instance namespace.
如果上面的app還有一個名為'polls'的默認(rèn)實(shí)例,上面的第二種情況'polls:index'將解析到該默認(rèn)實(shí)例,而不是 urlpatterns 中最后聲明的實(shí)例.
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選