所以我在Django教程第4章的最后也得到了noReverseMatch错误。但在我的案例中,其他答案似乎都没有帮助。而且我无法理解为什么教程会提供一些无效的东西。
我自己输入所有内容,所以某处肯定会有拼写错误,但我已经尝试用第4章中的复制/粘贴交换所有代码,而且我仍然遇到同样的错误:
这是错误:
NoReverseMatch at /polls/
Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$']
Error during template rendering
In template /home/MyName/tutorial/mysite/polls/templates/polls/index.html, error at line 4
Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$']
这是urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote')
]
这是views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
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': "You didn't select a choice",})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
这是index.html:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question_id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
答案 0 :(得分:5)
改变这个
{% url 'polls:detail' question.id %}
至Tanuki Java Service Wrapper
答案 1 :(得分:1)
您正在呈现question
以便访问其值,question.value
而不是question_value
:
用户{% url 'polls:detail' question.id %"
其中question.id是url的数字参数。