我是否需要在djangoproject教程4中渲染(请求...)或HttpResponseRedirect(反向...)

时间:2015-05-07 07:44:04

标签: python django

在djangoproject教程第4部分中,我收到以下错误:

  

/ polls / 1 / result /的NoReverseMatch   使用参数'('',)'和关键字参数'{}'反转'detail'   未找到。尝试了1种模式:[u'polls /(?P \ d +)/ $']

1   <h1>{{ question.question_text }}</h1>
2   
3   <ul>
4   {% for choice in question.choice_set.all %}
5       <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
6   {% endfor %}
7   </ul>
8   
9   <a href="{% url 'polls:detail' question.id %}">Vote again?</a>
10  

似乎我写了教程中的内容,是否有人知道可能出错的是什么?

我尝试了stackoverflow的其他方法,例如: Django 1.7.4: Error on Django 1.7 tutorial04: NoReverseMatch error for Reverse for 'vote'

http://djangotalk.blogspot.com/2014/12/re-reverse-for-results-with-arguments_2.html

但所有这些错误都可能指向不同的事情

我的代码如下:

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

views.py:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext, loader
from polls.models import Question, Choice
from django.http import Http404
from django.core.urlresolvers import reverse


def index(request):
    latest_question_list =  Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = RequestContext(request, {'latest_question_list' : latest_question_list, })
    return HttpResponse(template.render(context))

def detail(request, question_id):
    try:
        question = Question.objects.get(pk = question_id)
    except Question.DoesNotExist:
        raise Http404("Question ne postoji")
    return render(request, 'polls/detail.html', {'question': question})

def results(request, question_id):
    question = get_object_or_404(Question, pk = question_id)
    return render(request, 'polls/results.html', {'guestion': question})


def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice  = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "Did not choose answer.",
         })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

1 个答案:

答案 0 :(得分:1)

您的results视图有拼写错误:

return render(request, 'polls/results.html', {'guestion': question})
                                               ^ g instead of q

因此,您的模板没有question值,因此反向URL解析失败 - 您可以看到错误消息显示它正在传递id的空白值,而不是值question.id