1

我正在尝试访问详细视图,但它似乎没有正确映射。有什么我想念的吗?当我尝试访问 localhost:8000/polls/1 视图时,我得到一个 404 表示 url 模式与下面给出的任何这些 url 模式都不匹配。我的正则表达式有问题吗?

以下是 404 中的 url 模式:

^polls/ ^$
^polls/ ^polls/(?P<poll_id>\d+)/$
^polls/ ^polls/(?P<poll_id>\d+)/results/$
^polls/ ^polls/(?P<poll_id>\d+)/vote/$
^admin/

当前 URL polls/1/vote/ 与其中任何一个都不匹配。

这是 urls.py:

from django.conf.urls import patterns, include, url

urlpatterns = patterns('polls.views',
    url (r'^$', 'index'),
    url (r'^polls/(?P<poll_id>\d+)/$', 'detail'),
    url (r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
    url (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
    )

这是我的views.py:

from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Choice,Poll

def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p},
                                  context_instance=RequestContext(request))

def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/results.html', {'poll':p})

def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
    selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
    #Redisplay poll voting form
    return render_to_response('polls/detail.html', {
        'poll': p,
        'error_message': "You didn't select a choice.",
    }, context_instance=RequestContext(request))
else:
    selected_choice.votes += 1
    selected_choice.save()
return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
4

1 回答 1

0

我猜您在项目 urls 文件中包含您的应用程序 url,这就是为什么在错误 url 中您可以看到两次写入的民意调查。我建议您从您的应用程序网址中删除“民意调查”字样,然后重试..

    url (r'^$', 'index'),
    url (r'^(?P<poll_id>\d+)/$', 'detail'),
    url (r'^(?P<poll_id>\d+)/results/$', 'results'),
    url (r'^(?P<poll_id>\d+)/vote/$', 'vote'),
于 2012-12-04T02:04:32.623 回答