如何在Django中显示视图?

2024-05-14 06:02:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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.

我做错了什么,不能在浏览器中显示简单的消息?你知道吗


Tags: djangofrompyimporthttpurlindexinclude
1条回答
网友
1楼 · 发布于 2024-05-14 06:02:56

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

a prefix to apply to each view function

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

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

相关问题 更多 >