如何在Django中显示视图?

时间:2013-12-11 23:12:48

标签: python django

我对Django完全不熟悉,我正在努力了解它是如何工作的(我更习惯于PHPSpring框架。 我有一个名为testrun的项目,其中有一个名为graphs的应用,所以我的views.py看起来像:

#!/usr/bin/python
from django.http import HttpResponse

def index(request):
   return HttpResponse("Hello, World. You're at the graphs index.")

然后,在graphs/urls.py

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

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

最后,在testrun/urls.py

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

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'testrun.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^graphs/', include('graphs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

但是,当我尝试访问http://127.0.0.1:8000/graphs/时,我得到了:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/graphs/
Using the URLconf defined in testrun.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, graphs/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

我做错了什么我无法在浏览器中显示那条简单的信息?

1 个答案:

答案 0 :(得分:2)

要扩展我的评论,patterns()函数的第一个参数是

  

应用于每个视图函数的前缀

您可以在此处找到更多信息:

https://docs.djangoproject.com/en/dev/topics/http/urls/#syntax-of-the-urlpatterns-variable

因此,在graphs/urls.py中你需要像这样修复模式调用:

urlpatterns = patterns('', # <-- note the `'',`
   url(r'^$', views.index, name='index'),
)