Any /polls URL always call index() function in views.py

一个人想着一个人 提交于 2019-11-28 14:44:43

Firstly, it's really important to make sure that you are following the tutorial that matches your version of Django. Here are the links for Django 2.0 and Django 1.11.

You are getting the unexpected behaviour because you are mixing the old url and new path syntax. If you are using Django 2.0, change the import and update your URL patterns:

from django.urls import path

urlpatterns = [

    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),

    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),

]

If you are using an earlier version of Django, you need to use regexes instead. For example, the Django 1.11 tutorial gets you to write:

from django.conf.urls import url

urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

Which version of Django is this? Your url patterns look like a mixture of 2.0 and older routing.

Your empty url pattern would probably match anything so not another route ever gets called.

For Django 2.0 + do what @Alasdair suggest above for older Django version something like below:

urlpatterns = [
    url(r'^$', views.index, name='index'),
] 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!