Django 1.11 Polls应用配置视图时出现404错误求助
polls/1 in Django 1.11 Hey there, let's break down why you're seeing that 404 error when trying to access http://localhost:8000/polls/1—it's all about how your URL patterns are set up!
Let's look at the error clue
From your 404 page, Django tells us it tried these URL patterns:
^polls/ ^$ [name='index']
^polls/ ^(?P<question_id>[0-9]+)/$, [name='detail']
^polls/ ^(?P<question_id>[0-9]+)/results/$, [name='results']
^polls/ ^(?P<question_id>[0-9]+)/vote/$, [name='vote']
^admin/
The key issue here is the detail pattern: ^(?P<question_id>[0-9]+)/$. The trailing /$ means it only matches URLs that end with a slash—so polls/1/ (with a slash at the end) would work, but polls/1 (without the slash) doesn't match any pattern.
Here are 3 ways to fix this:
Use the trailing slash in your URL
Just visithttp://localhost:8000/polls/1/instead ofpolls/1—this should immediately match thedetailview as defined in your URLconf. This aligns with Django's default URL design convention (treating URLs like directories with trailing slashes).Adjust the URL pattern to accept optional trailing slash
Open yourpolls/urls.pyfile, and modify the detail path pattern from:url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),To:
url(r'^(?P<question_id>[0-9]+)/?$', views.detail, name='detail'),The
?after the slash makes it optional, so bothpolls/1andpolls/1/will now match the detail view.Verify the
APPEND_SLASHsetting
Check yoursettings.pyfile for theAPPEND_SLASHoption. Django defaults this toTrue, which automatically redirects requests without trailing slashes to the version with the slash (sopolls/1would redirect topolls/1/). If you've setAPPEND_SLASH = False, this redirect won't happen—just change it back toTrueand restart your server to fix the issue.
内容的提问来源于stack exchange,提问作者CoderMACi5

