Django教程中的页面未找到(404)

1 投票
1 回答
986 浏览
提问于 2025-04-17 15:10

我正在学习这个教程:https://docs.djangoproject.com/en/1.4/intro/tutorial02/

我把urls.py文件改成了:

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

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
      url(r'^admin/', include(admin.site.urls)),
)

当我启动runserver的时候,出现了以下内容:

404 error

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, , didn't match any of these.

我是不是哪里做错了?

提前谢谢你,

比尔

1 个回答

2

你没有定义基本的网址。你需要类似这样的东西 -

urlpatterns = patterns('',

    # ...
    url(r'^$', HomeView.as_view())

)

你应该能在这个地址看到你的网站 - localhost:8000/admin/(假设你是用 python manage.py runserver 启动的开发服务器)。

Django会检查你在网址配置文件中定义的所有网址,然后看看有没有和你在浏览器中输入的网址匹配的。如果找到了匹配的网址,它就会返回对应视图的http响应(上面代码中的HomeView)。urls.py文件就是用来把网址和视图对应起来的。视图会返回http响应。

从你收到的错误信息(以及你在url.py文件中包含的代码)来看,你的应用中只定义了一个网址 - admin/。如果你尝试访问其他网址,就会失败。

想了解更多信息,可以查看 Django的URL调度文档

撰写回答