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

Python Django教程:完成第一页后出现无法解释的404错误,python,django,Python,Django,我做完了 预期行为有效。我的民调指数正在显示。但有一个意想不到的后果,我不明白。当我转到localhost:8000时,我得到一个找不到的页面。为什么? 这是我的mysite/mysite/url.py,如教程所述 from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), ur

我做完了

预期行为有效。我的民调指数正在显示。但有一个意想不到的后果,我不明白。当我转到
localhost:8000
时,我得到一个找不到的页面。为什么?

这是我的
mysite/mysite/url.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),
]
服务器说:

Not Found: /
[11/Feb/2016 04:25:46] "GET / HTTP/1.1" 404 2010
Not Found: /
[11/Feb/2016 04:24:23] "GET / HTTP/1.1" 200 1767
当我删除投票行时,404将消失。即:

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
现在服务器说:

Not Found: /
[11/Feb/2016 04:25:46] "GET / HTTP/1.1" 404 2010
Not Found: /
[11/Feb/2016 04:24:23] "GET / HTTP/1.1" 200 1767

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

本教程没有定义当你转到你的站点根目录时会发生什么,它只处理
轮询
应用程序。如果您想在浏览
http://localhost:8080/

作为一个简单的示例,请尝试在您的
mysite/url.py
中进行以下更改:

from polls import views

urlpatterns = [
    url(r'^$', views.index, name='site_index'),
    ...
]
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

从现在开始,当你浏览到你的站点根目录时,你应该会看到
轮询
应用程序的索引视图。

有趣的观察!我以前从没注意过

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

但是如果没有定义URL模式,django将打印您在
runserver
shell中看到的
notfound:{URL}
。它将尝试引发404异常,正如预期的那样

但是在
debug
模式下,它会做一些额外的工作。 让我们在
django/views/debug.py
中检查此函数:

from polls import views

urlpatterns = [
    url(r'^$', views.index, name='site_index'),
    ...
]
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
Django在这里试图做的是检查它尝试了多少URL模式。如果满足特定条件,它将尝试通过
default\u urlconf
返回。 这些具体条件是:

  • 如果没有定义URL模式
  • 如果尝试的URL为“/”,并且唯一定义的URL模式是针对
    admin
    应用程序的
因此,我们从这里了解到,如果没有定义URL模式,Django将始终调用
default\u urlconf
。尝试删除
admin
URL,然后访问任意URL。你总会得到这样的结果:

Not Found: /random/url/
[11/Feb/2016 04:24:23] "GET /random/url/ HTTP/1.1" 200 1767
现在让我们看看
default\u urlconf
code:

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

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

以防遇到与我类似的问题

我正在用django rest框架构建一个API。终结点希望使用令牌对当前用户进行身份验证。我正在使用

我意识到我的问题是从前端以错误的格式传递令牌,因此用户被呈现为匿名用户

  Get(endpoint) {
    if (this.token !== null) {
      let auth = `bearer ${this.token}`;
      let headers = new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: auth
      });

      let fullurl = `${this.baseUrl}${endpoint}`;
      return this.http
        .get(fullurl, { headers: headers })
        .pipe(catchError(this.handleError));
    }
  }

将Bear更改为Bear,因为这应该可以解决问题。

感谢您的明确解释。我还测试了代码,它是有效的:)除了一个可靠的解释,这个答案真正有价值的是,你告诉我下次如何解决这样的问题。调查来源。我错过了那一点,谢谢:)