本文介紹了django反向解析URL和URL命名空間俏拱,分享給大家,具體如下:
首先明確幾個概念:
1.在html頁面上的內(nèi)容特別是向用戶展示的url地址,比如常見的超鏈接,圖片鏈接等,最好能動態(tài)生成,而不要固定.
2.一個django項目中一般包含了多個django應(yīng)用(app).
3.一個視圖(view)往往對應(yīng)多個url地址.
在django中實現(xiàn)反向解析URL必備條件就是 url和view能一對一 的匹配.
(通過view找到唯一一個對應(yīng)的url,通過url也能找到唯一一個view)
最簡單的方式 就是使用 name
,可以理解為url起了一個名字.
例如:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/([0-9]{4})/$', views.year_archive, name='news-year-archive'),
]
此時的 news-year-archive
就可以表示 /articles/yyyy/
在view中進(jìn)行使用.
在templates中使用
<a href="{% url 'news-year-archive' 2012 %}" rel="external nofollow" >2012 Archive</a>
在view中使用
from django.urls import reverse
from django.http import HttpResponseRedirect
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
但是使用 name
也存在一定的 問題 ,比如在同一個項目中的不同的app中 name
可能會重名(導(dǎo)致反解析時一個view對應(yīng)多個url),而且給每一個url起不同名字也很繁瑣.
這時候就會用到 URL命名空間
URL命名空間包括兩個部分: app_name ( 應(yīng)用命名空間 )以及 namespace ( 實例命名空間 )
對于 app_name 官方解釋"它表示正在部署的應(yīng)用的名稱。一個應(yīng)用的每個實例具有相同的應(yīng)用命名空間",比較好理解碉就,也就是說可以通過設(shè)置 app_name
來區(qū)分不同app中同名的 name 了,使用 : 連接躺孝。
但是對于 namespace 官方解釋"它表示應(yīng)用的一個特定的實例。 實例的命名空間 在你的全部 項目中 應(yīng)該是 唯一 的底桂。但是植袍,一個實例的命名空間可以和應(yīng)用的命名空間相同",就比較的難以理解籽懦,namespace
主要功能為了區(qū)分同一個app下不同實例,使得反解析url時能獲得正確的結(jié)果于个。
例如:
在不加入 namespace 時,訪問 http://127.0.0.1:8000/ccc/aaa/ 和 http://127.0.0.1:8000/bbb/aaa/
結(jié)果均為 /ccc/aaa/ ,這顯然不是我們想要獲取的結(jié)果。
# 主url.py
urlpatterns = [
...
url(r'^bbb/', include("test_namespace2.urls")),
url(r'^ccc/', include("test_namespace2.urls")),
...
]
# test_namespace2/url.py
app_name = "app02"
urlpatterns = [
url(r'aaa/$', views.aaa, name="index"),
]
# test_namespace2/view.py
def aaa(request):
return HttpResponse(reverse("app02:index"))
做出一些修改,加入namespace
用作區(qū)別
# 主url.py
urlpatterns = [
...
url(r'^bbb/', include("test_namespace2.urls", namespace='bbb')), # 加入了namespace
url(r'^ccc/', include("test_namespace2.urls", namespace='ccc')),
...
]
# test_namespace2/view.py
def aaa(request):
return HttpResponse(reverse("app02:index", current_app=request.resolver_match.namespace)) # 使用namespace
這樣就會獲得正確的結(jié)果了暮顺。
首先在,主url.py中添加 namespace
urlpatterns = [
url(r'^polls/', include('polls.urls',namespace='test')),
]
然后要在app的urls.py中添加 app_name
和 name
比如:
app_name = 'polls'
urlpatterns = [
#...
url(r'^$', views.index, name='index'),
#...
然后在view和templates中使用app_name:name
,此時就算有多個app中都有名為 index 的 name 也不會有問題了
在view中使用:
reverse(``'polls:index'``, current_app``=``request.resolver_match.namespace)
在templates中使用
{``%` `url` `'polls:index'` `%``}