Django教程:完成第一页后出现无法解释的404错误

Mel*_*est 4 python django

我完成了https://docs.djangoproject.com/en/1.9/intro/tutorial01/

预期的行为有效.我的民意调查指数正在显示.但是有一个我无法理解的意外后果.当我去的时候,localhost:8000我找不到一个页面.为什么?

这是我mysite/mysite/urls.py的教程解释.

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

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]
Run Code Online (Sandbox Code Playgroud)

服务器说:

Not Found: /
[11/Feb/2016 04:25:46] "GET / HTTP/1.1" 404 2010
Run Code Online (Sandbox Code Playgroud)

当我删除民意调查行时,404消失.即:

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
Run Code Online (Sandbox Code Playgroud)

现在服务器说:

Not Found: /
[11/Feb/2016 04:24:23] "GET / HTTP/1.1" 200 1767
Run Code Online (Sandbox Code Playgroud)

所以我想这是一些默认的怪癖,但我仍然不完全知道我是否犯了错误或者这是否是定义的行为.我的其他代码与本教程的代码片段相同.

jat*_*jit 5

有趣的观察!之前没有注意到.

当您访问URL时,Django会尝试将其与所有已定义的模式(按定义顺序)匹配.对于匹配的第一个模式,将调用相应的视图.

但如果没有定义URL模式,那么django将打印Not found: {url}您在runservershell中看到的内容.并且它会像预期的那样尝试提出404异常.

但在这种debug模式下,它确实有点多余.我们来看看这个函数django/views/debug.py:

def technical_404_response(request, exception):
    # some extra code here
    if (not tried                           # empty URLconf
        or (request.path == '/'
            and len(tried) == 1             # default URLconf
            and len(tried[0]) == 1
            and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
        return default_urlconf(request)
    # more extra code here
Run Code Online (Sandbox Code Playgroud)

Django试图在这里做的是检查它尝试了多少个URL模式.如果特定条件满足,它将尝试通过default_urlconf.这些具体条件是:

  • 如果没有定义URL模式
  • 如果尝试过的URL是"/",则定义的唯一URL模式适用于该admin应用

所以我们从这里学到的是,如果没有定义URL模式,那么Django将始终调用default_urlconf.尝试删除adminURL,然后访问任何随机URL.你总会得到这样的东西:

Not Found: /random/url/
[11/Feb/2016 04:24:23] "GET /random/url/ HTTP/1.1" 200 1767
Run Code Online (Sandbox Code Playgroud)

现在让我们看一下default_urlconf代码:

def default_urlconf(request):
    "Create an empty URLconf 404 error response."
    t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE)
    c = Context({
        "title": _("Welcome to Django"),
        "heading": _("It worked!"),
        "subheading": _("Congratulations on your first Django-powered page."),
        "instructions": _("Of course, you haven't actually done any work yet. "
            "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."),
        "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your "
            "Django settings file and you haven't configured any URLs. Get to work!"),
    })

    return HttpResponse(t.render(c), content_type='text/html')
Run Code Online (Sandbox Code Playgroud)

(它返回一个正确的HttpResponse=> 200 HTTP代码)