【问题标题】:Django 1.7.4: Error on Django 1.7 tutorial04: NoReverseMatch error for Reverse for 'vote'Django 1.7.4:Django 1.7 tutorial04 上的错误:“投票”的 Reverse 出现 NoReverseMatch 错误
【发布时间】:2015-02-08 15:20:52
【问题描述】:

我整个早上都在努力完成 Django 1.7 教程04。我已经阅读了 stackoverflow 上关于 NoReverseMatch 错误的所有类似帖子,我的错误略有不同:

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>

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

我的 polls/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

任何帮助将不胜感激。感谢您的阅读。

【问题讨论】:

    标签: python django


    【解决方案1】:

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

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

    【讨论】:

    • 真是个愚蠢的错误!我习惯于使用 _s 作为主键 ID 来处理手动 sql 查询。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多