2015-11-09 62 views
0

所以我也在Django教程的第4章最後得到了noReverseMatch錯誤。但其他答案似乎沒有幫助我的情況。我不明白爲什麼教程會提供一些不起作用的東西。NoReverseMatch Django教程1.8第4章

我輸入的一切我自己,所以肯定會在某個地方一個錯字,但我試過從第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 %} 

回答

5

更改此 {% url 'polls:detail' question_id %}{% url 'polls:detail' question.id %}

+0

是的,就是這樣。我感到很蠢,因爲沒有抓住它,但很高興它只是一個小而容易的解決方案。非常感謝。 – Exodus111

1

要渲染question所以要訪問它的價值應該是question.valuequestion_value

用戶{% url 'polls:detail' question.id %"

其中question.id是url的數字參數。

+0

是的,就是這樣。 謝謝先生。 – Exodus111

+0

@ Exodus111:如果您在回答時發現此問題,則必須用綠色標記標出。隨時歡迎 –