polls/urls/py
from django.conf.urls import url
from . import views
urlpatterns = [
url('', views.index, name='index'),
url('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
url('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
url('<int:question_id>/vote/', views.vote, name='vote'),
]
views.py
from __future__ import unicode_literals
from django.http import HttpResponse
from .models import Question
from django.template import loader
# from django.shortcuts import render
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
URL = http://127.0.0.1:8000/polls
URL = http://127.0.0.1:8000/polls/1/
URL = http://127.0.0.1:8000/polls/1/results
这些所有网址都提供相同的映射相同的函数index()。任何帮助将不胜感激
答案 0 :(得分:1)
首先,要确保您遵循与您的Django版本相匹配的教程,确实非常重要。以下是Django 2.0和Django 1.11的链接。
您正在收到意外行为,因为您正在混合使用旧的url
和新path
语法。如果您使用的是Django 2.0,请更改导入并更新您的URL模式:
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'),
]
如果您使用的是早期版本的Django,则需要使用正则表达式。例如,Django 1.11教程可以让你写:
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'),
]
答案 1 :(得分:0)
这是哪个版本的Django?您的网址格式看起来像2.0和旧版路由的混合。
您的空网址模式可能会匹配任何内容,因此不会调用其他路由。
对于Django 2.0 +做@Alasdair上面提到的更老的Django版本,如下所示:
urlpatterns = [
url(r'^$', views.index, name='index'),
]