Django 1.7.4:Django 1.7上的错误教程04:反向投票的NoReverseMatch错误

时间:2015-02-08 15:20:53

标签: python django

我整个上午一直在试着完成Django 1.7教程04。我已经阅读了有关NoReverseMatch错误的stackoverflow上的所有类似帖子,我的错误略有不同:

Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<question_id>\\d+)/vote/$']

我的details.html表单操作属性似乎令人窒息:

<body bgcolor="white">
    <h1>{{ question.question_text }}</h1>
    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

    <form action="{% url 'polls:vote' question_id %}" method="post">
    {% csrf_token %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
        <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
    {% endfor %}
        <input type="submit" value="Vote" />
    </form>
</body>

我已经在我的主网址中定义了民意调查命名空间,并在我的民意调查索引页面上工作 - ul li中的a标签正在使用{% url 'polls:detail' question.id %}并且它工作得很好。

我的民意调查/ urls.py看起来像:

from django.conf.urls import patterns, url

from polls import views

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 render, get_object_or_404
from django.http import HttpResponse,Http404
from django.http import HttpResponseRedirect, HttpResponse

from polls.models import Question,Choice

# Create your views here.

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

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

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

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):
        # redisplay the question voting form
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        select_choice.save()
        # always return response redirect after dealing with POST 
        # to prevent reposts if user hits back button
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

错误:

NoReverseMatch at /polls/1/

Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<question_id>\\d+)/vote/$']

Request Method:     GET
Request URL:    http://localhost:8000/polls/1/
Django Version:     1.7.4
Exception Type:     NoReverseMatch
Exception Value:    

Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<question_id>\\d+)/vote/$']

Exception Location:     /usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 468
Python Executable:  /usr/bin/python
Python Version:     2.7.9

非常感谢任何帮助。谢谢你的阅读。

1 个答案:

答案 0 :(得分:2)

而不是question_id,请尝试在模板中使用question.id,即:

<form action="{% url 'polls:vote' question.id %}" method="post">