求助:所有Polls系列URL均错误映射至views.py的index()函数
Hey there, let's get those URLs pointing to the right views! This is a super common issue usually caused by either missing regex anchors or misconfigured URL patterns. Here's how to fix it step by step:
1. Fix Your Polls App's urls.py
This is where the problem is almost certainly happening. You need to make sure each URL pattern is explicitly mapped to the correct view, and that you're using proper matching rules so Django doesn't accidentally route everything to index().
If you're using Django's path() function (recommended for modern Django):
Update your polls/urls.py to look like this:
from django.urls import path from . import views urlpatterns = [ # Exact match for /polls/ → index() path('', views.index, name='index'), # Matches /polls/1/, /polls/2/, etc. → detail() path('<int:question_id>/', views.detail, name='detail'), # Matches /polls/1/results/, /polls/2/results/, etc. → results() path('<int:question_id>/results/', views.results, name='results'), ]
If you're using re_path() (old-style regex routing):
If you're sticking with regex, you must use the $ anchor to mark the end of the URL—otherwise, any URL starting with your pattern will match. Here's the correct setup:
from django.urls import re_path from . import views urlpatterns = [ # Exact match for /polls/ re_path(r'^$', views.index, name='index'), # Exact match for /polls/1/ re_path(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # Exact match for /polls/1/results/ re_path(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), ]
2. Double-Check Your Project's Root urls.py
Make sure your project's main URL config is correctly delegating polls-related URLs to the app's URLconf. It should look like this:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), # Send all /polls/ requests to the polls app's URLs path('polls/', include('polls.urls')), ]
The include() function is key here—it tells Django to look inside polls/urls.py for the rest of the URL path, instead of trying to handle everything in the root config.
Common Mistakes You Might Have Made
- Missing the
$anchor in regex: If you had something likere_path(r'^polls/', views.index), any URL starting with/polls/(including/polls/1/and/polls/1/results) would route toindex()—that's exactly what you're seeing! - Wrong order of patterns: Django checks URL patterns top to bottom. If you put a broad pattern (like matching any string) before specific ones, the broad one will catch all requests. Always put more specific patterns first.
- Skipping
include(): If you directly mapped/polls/toviews.indexin the root URLconf without usinginclude, all subpaths under/polls/would still go toindex()unless you added separate patterns for each one.
Once you make these changes, restart your Django server and test each URL again—they should now route to the correct view functions.
内容的提问来源于stack exchange,提问作者Manish kumar

