1

I'm hitting the following error when going through the Django tutorial: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$']

From this answer it seems like the problem is that the argument is not being passed through on line 9 of results.html.

This answer suggests that it should be question.id but that's what I have. So I'm not sure where to go next on this. part following error. When I remove line 9 (which includes this link) from the template. Help appreciated. Apologies if this has already been asked before - I feel like I've looked everywhere.

Hopefully this is all the relevant code. (After this went wrong a couple of times I copied and pasted everything from the tutorial to guard against typos.)

Traceback

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/results/

Django Version: 2.0.3
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls.apps.PollsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Users\User\Dropbox\Personal\Projects\Python\Django\django-tut\mysite\polls\templates\polls\results.html, error at line 8
   Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$']
   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 : <a href=" {% url 'polls:detail' question.id %} ">Vote again?</a>
   9 : 

Traceback:

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\User\Dropbox\Personal\Projects\Python\Django\django-tut\mysite\polls\views.py" in results
  19.     return render(request, 'polls/results.html', {question:question})

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\loader.py" in render_to_string
  62.     return template.render(context, request)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\base.py" in render
  175.                     return self._render(context)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\base.py" in _render
  167.         return self.nodelist.render(context)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\base.py" in render
  943.                 bit = node.render_annotated(context)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\base.py" in render_annotated
  910.             return self.render(context)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\template\defaulttags.py" in render
  447.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\urls\base.py" in reverse
  88.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  632.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /polls/1/results/
Exception Value: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$']

polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

mysite/urls.py

from django.urls import include, path
from django.contrib import admin

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
    #path('<int:question_id>/', views.detail, name='detail'),
]

polls/results

    <h1>{{ question.question_text }}</h1>

    <ul>
    {% for choice in question.choice_set.all %}
        <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
    {% endfor %}
    </ul>
    <a href="{% url 'polls:detail' question.id %}">Vote again?</a>

polls/views.py

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse

from .models import Choice, Question


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):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {question:question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
  • Where is the view? Are you passing anything called "question" to the template? Does it have an id? – Daniel Roseman May 02 '18 at 20:11
  • Sorry - added the whole `polls/views.py` now. I believe (although am not certain) that it does at line 37 `return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))` – mbanerjeepalmer May 02 '18 at 20:16

1 Answers1

1

Wow, this one took me a while to spot. You have a typo in the last line of your results function. This:

return render(request, 'polls/results.html', {question:question})

should be:

return render(request, 'polls/results.html', {"question": question})

with quotes around the first question.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895