2010-01-24 83 views
29

我正在尋找一個很好的Django中的URL命名空間教程。我發現官方文檔有點太稀疏 - 它缺乏很好的例子。我在這裏找到了similar question,但答案並沒有幫助我完全理解這個主題。任何人都知道好的Django URL命名空間教程?

+0

您是否檢查過https://docs.djangoproject.com/en/1.3/topics/http/urls/#naming-url-patterns中的url dispatcer doc我建議您閱讀整個部分,因爲如果您瞭解有關它如何工作的基礎知識,那麼它會更容易理解 – FallenAngel 2011-05-28 10:33:33

+5

@FallenAngel:我的觀點仍然存在 - 在官方文檔中沒有使用名稱空間的好例子。 – minder 2011-06-12 10:48:43

回答

33

同意,這個文檔相當混亂。這裏是我的它的讀數(注:所有的代碼是未經測試!):

apps.help.urls

urlpatterns = [ 
    url(r'^$', 'apps.help.views.index', name='index'), 
    ] 

在你的主urls.py

urlpatterns = [ 
    url(r'^help/', include('apps.help.urls', namespace='help', app_name='help')), 
    url(r'^ineedhelp/', include('apps.help.urls', namespace='otherhelp', app_name='help')), 
    ] 

在模板:

{% url help:index %} 

應該產生url /help/

{% url otherhelp:index %} 

應該產生的URL /ineedhelp/

{% with current_app as 'otherhelp' %} 
    {% url help:index %} 
{% endwith %} 

應同樣產生url /ineedhelp/

同樣,reverse('help:index')應產生/help/

reverse('otherhelp:index')應產生/ineedhelp/

reverse('help:index', current_app='otherhelp')也應該產生/ineedhelp/

就像我說的,這是基於我對文檔的閱讀以及我對Django-land中工作傾向的熟悉程度。我沒有花時間來測試這個。

+0

爲什麼我們需要app_name和命名空間都設置?只是想知道。 似乎它也適用於未設置app_name – 2012-10-03 06:26:38

+0

由於文檔[讓我相信他們是必要的](https://docs.djangoproject.com/en/1.4/topics/http/urls/#defining-url-namespaces )。即使文檔錯誤或誤導,如果文檔中包含「app_name」,以防未來行爲發生變化以匹配文檔,它可能更具前瞻性。如果你真的想知道爲什麼,你必須閱讀代碼。 – 2012-10-04 16:18:34

+0

好的建議我通常儘量閱讀儘可能多的來源,但不能直接找到相關部分,會做更多的挖掘。閱讀之前有一篇好文章說:源頭從不說謊,但手冊可能會做。他基本上告訴人們,如果他們遇到問題或者使用錯誤的hehe來閱讀源代碼。 – 2012-10-05 04:54:17

0

這是從文檔

(r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')), 

也許你應該更具體的瞭解你正在嘗試做的。

相關問題