使用 Django 将 URL 映射到站点根目录

Mapping URLs to Site Root with Django

我目前有一个名为 "misc" 的 Django 应用程序,其中有我的站点索引页面以及一些其他页面(其中大部分包含静态信息)。现在我的 misc/views.py 看起来像这样:

def index(request):     
    return render(request, 'misc/index.html', {})

def why(request):
    return render(request, 'misc/why.html', {}) 

我在 misc/urls.py 中的 urlpatterns 看起来像这样:

url(r'^$', views.index, name='index'),
url(r'^why/$', views.why, name='why'),   

和我的 main urls.py 看起来像这样:

url(r'^$', include('misc.urls')),

所以当我转到 http://127.0.0.1:8000/ I see my index page just fine, however when I go to http://127.0.0.1:8000/why/ 时,我没有看到我的 why.html 页面,只是一个 "Page not found" 错误。关于如何解决这个问题的任何想法?谢谢。

您的 url 模式匹配空字符串:

url(r'^$', include('misc.urls')),

^ 匹配字符串的开头,$ 匹配结尾,因此只有完全空的字符串才有效。正如 Dima 在评论中指出的那样,删除 $ 它将起作用。