2013-05-14 108 views
3

我有一個簡單的django設置,其中有一個名爲'的列表'的應用程序。我現在想要http://127.0.0.1:8000/lists來顯示這個應用程序。所以我改變了我的主urls.py以下內容:無法讓django網址工作

from django.conf.urls import patterns, include, url 

from django.contrib import admin 
admin.autodiscover() 

urlpatterns = patterns('', 
    url(r'^lists/', include('lists.urls')), 
    url(r'^admin/', include(admin.site.urls)), 
) 

,我改變了(我的應用程序被稱爲列表),駐留在列表文件夾下面的urls.py:

from django.conf.urls import patterns, url 
from lists import views 

urlpatterns = patterns(
    url(r'^$', views.index, name='index') 
) 

據我知道我下面在the django tutorial的說明非常清楚,但是當我訪問http://127.0.0.1:8000/lists沒有斜線),它給了我下面的錯誤:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/lists 

Using the URLconf defined in companyLists.urls, Django tried these URL patterns, in this order: 

    ^lists/ 
    ^admin/ 

The current URL, lists, didn't match any of these. 

,當我參觀http://127.0.0.1:8000/lists/結尾的斜線)它給了我下面的錯誤:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/lists/ 

Using the URLconf defined in companyLists.urls, Django tried these URL patterns, in this order: 

    ^admin/ 

The current URL, lists/, didn't match any of these. 

我不明白爲什麼它不搜索^列表/再當我訪問的網址與尾隨斜線。有人知道我在這裏做錯了嗎?

歡迎所有提示!

回答

11

您錯過了patterns列表urls.py開頭的空字符串。

試試這個:

urlpatterns = patterns('', 
    url(r'^$', views.index, name='index') 
) 

的空字符串是一個view prefix,你可以用它來協助DRY原則。它用於爲視圖路徑添加前綴。相反

比有:

例如,(上方延伸的例子)

urlpatterns = patterns('', 
    url(r'^$', views.index, name='index'), 
    url(r'^homepage$', views.homepage, name='index'), 
    url(r'^lists$', views.lists, name='index'), 
    url(r'^detail$', views.detail, name='index'), 
) 

您可以使用:

urlpatterns = patterns('views', 
    url(r'^$', index, name='index'), 
    url(r'^homepage$', homepage, name='index'), 
    url(r'^lists$', lists, name='index'), 
    url(r'^detail$', detail, name='index'), 
) 

要有multiple view prefixes只是細分urlpatterns

urlpatterns = patterns('views', 
    url(r'^$', index, name='index'), 
    url(r'^homepage$', homepage, name='index'), 
    url(r'^lists$', lists, name='index'), 
    url(r'^detail$', detail, name='index'), 
) 

urlpatterns += patterns('more_views', 
    url(r'^extra_page$', extra_page, name='index'), 
    url(r'^more_stuff$', something_else, name='index'), 
) 
+0

啊,我忽略了這一點。這確實有效!但最重要的是;爲什麼?爲什麼在開始時需要一個空字符串? – kramer65 2013-05-14 16:16:09

+0

現在更新了我的答案@ kramer65 - 希望能讓它更清晰。 – Ewan 2013-05-14 16:21:45