Django 路由 - 空路径与其中任何一个都不匹配

Django routing - The empty path didn't match any of these

非常基本的问题,令我惊讶的是我找不到答案。我刚刚开始研究 django 并进行了开箱即用的安装。创建了一个项目并创建了一个应用程序。 urls.py的默认内容很简单:

urlpatterns = [
    path('admin/', admin.site.urls),
]

如果我打开 django 站点主页,我会看到带有火箭图片的内容。但是,正如我所说,我在项目中创建了另一个应用程序,假设名为“bboard”。我在 bboard/views.py

中创建了一个简单的 'hello world' 函数
def index(request):
    return HttpResponse('Hello world')

为了能够通过浏览器访问,我修改了原来的urls.py文件如下:

from bboard.views import index
urlpatterns = [
    path('admin/', admin.site.urls),
    path('bboard/', index),
]

这样我可以访问 localhost:port/adminlocalhost:port/bboard URL s,但是如果我现在尝试使用 localhost:port 打开主页,我会收到 Page not found 错误。

使用 samplesite.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式: 行政/ 板/ 空路径与其中任何一个都不匹配。

如果我注释掉 urlpatterns 列表中的第二项,一切正常。那么为什么额外的模式会影响这一点,需要做什么来解决它?

您需要在根 urls.py

中添加一个空 url
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('bboard.urls'))
]

在您添加自己的路由之前,Django 将提供位于“/”的默认主页 url。添加自己的路由配置后,django 不再提供其默认示例主页。

来自 django 的 django/views/debug.py:

def technical_404_response(request, exception):
    """Create a technical 404 error response. `exception` is the Http404."""
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried or (                  # empty URLconf
            request.path == '/' and
            len(tried) == 1 and             # default URLconf
            len(tried[0]) == 1 and
            getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
        )):
            return default_urlconf(request)

注意最后的 else 块 returns 一个 default_urlconf 如果包含的唯一 url 路径是管理路径并且请求的 url 是 /。此 default_urlconf 是您提到的示例 Rocket 页面。只要您添加任何自己的路由,else 块中的 if 语句就会为 false,因此 default_urlconf 不会返回,而是落入正常的 404 处理程序。

这是default_urlconf

def default_urlconf(request):
    """Create an empty URLconf 404 error response."""
    with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
        t = DEBUG_ENGINE.from_string(fh.read())
    c = Context({
        'version': get_docs_version(),
    })

    return HttpResponse(t.render(c), content_type='text/html')

您可能收到此错误的另一个原因是 1:You 尚未在您的应用程序中传递空 URL URL 2:KIndly请问这是一个简单但非常关键的问题 检查你的错别字 我希望这个有帮助 问候