2017-06-13 86 views
0

我正在关注Django介绍性教程,并且我遇到了一个奇怪的错误。或者至少我认为这是一个奇怪的错误。
我在part 3,这是写更多的意见。尽我所能,我已经尽力了,接着写了一封教程。Django URLConf没有正确解决

/polls/urls.py文件看起来像这样:

from django.conf.urls import url 

from . import views 

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

if __name__ == "__main__": 
    pass 

而且polls/views.py看起来是这样的:

from django.http import HttpResponse 


def index(request): 
    return HttpResponse("Hello, world. You're at the polls index.") 


def detail(request, question_id): 
    return HttpResponse("You're looking at question {question}.".format(question=question_id)) 


def results(request, question_id): 
    response = "You're looking at the results of question {question}.".format(question=question_id) 
    return HttpResponse(response) 


def vote(request, question_id): 
    return HttpResponse("You're voting on question {question}.".format(question=question_id)) 


if __name__ == "__main__": 
    pass 

而且我在my_project/urls.py注册网址:

from django.conf.urls import include, url 
from django.contrib import admin 

urlpatterns = [ 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'^polls', include("polls.urls")) 
] 

如果我去http://127.0.0.1:8000/polls我看到“hello world”消息Ë我希望看到,但我尝试查找的问题之一,也就是我去http://127.0.0.1:8000/polls/1/我看到了以下错误消息:

Using the URLconf defined in learning_django.urls, Django tried these URL patterns, 
in this order: 

1. ^admin/ 
2. ^polls ^$ [name='index'] 
3. ^polls ^(?P<question_id>[0-9]+)/$ [name='detail'] 
4. ^polls ^(?P<question_id>[0-9]+)/results/$ [name='results'] 
5. ^polls ^(?P<question_id>[0-9]+)/vote/$ [name='vote'] 

The current URL, polls/1/, didn't match any of these. 

这怎么可能,我的网址不符合数3 ?这是一个基本的正则表达式。 enter image description here

+0

尝试使用/调查/ 1/ – digitake

回答

2

的问题是你的my_project/urls.pypolls后,你错过了/,更改为:

from django.conf.urls import include, url 
from django.contrib import admin 

urlpatterns = [ 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'^polls/', include("polls.urls")) # add/after polls 
] 
+0

你是我的英雄。我正在看错地方。 –

0

您可以使用Django的APPEND_SLASH设置(见here对于文件)或修改URL模式,使/可选,例如像这样:

url(r'^(?P<question_id>[0-9]+)/?$', views.detail, name='detail'),

+0

是否完全一样的事情。 –