无法让django网址发挥作用

时间:2013-05-14 16:04:48

标签: python django django-urls

我有一个简单的django设置,其中有一个名为' lists '的应用程序。我现在希望http://127.0.0.1:8000/lists显示此应用。所以我将主要的urls.py更改为以下内容:

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)),
)

我将位于lists-folder(我的app称为列表)的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.

我不明白为什么当我使用尾部斜杠访问url时它不再搜索^ lists /。有谁知道我在做错了什么?

欢迎所有提示!

1 个答案:

答案 0 :(得分: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'),
)