Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found

I'm following the official tutorial to learn Django and using 1.5.

I had this link as part of my index template, which was working fine:

<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

however, this is hardcoded and the tutorial suggested a better way was to use:

<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>

so that you'll be better of when dealing with huge number of templates and u have to make changes to the url.

Since I made the above change I get the following errors when I run the app:

Exception Type: NoReverseMatch
Exception Value:    Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found.

My urls.py looks like this:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
   url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),                     
)

views.py looks like this:

from django.shortcuts import render, get_object_or_404
from django.http import Http404

from polls.models import Poll

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


def detail(request, poll_id):
    poll = get_object_or_404(Poll, pk = poll_id)
    return render(request, 'polls/detail.html', {'poll': poll})

my index.html template looks like this:

{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="{% url 'polls:detail' poll_id %}">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p> No polls are available.</p>
{% endif %}

Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated.

like image 919
fromPythonImportNoob Avatar asked Oct 12 '13 15:10

fromPythonImportNoob


2 Answers

In your index.html you gave poll_id as an argument, but that's just the name the argument will have within the detail function; it is not defined in your template. The actual value you want to call the function with is probably poll.id.

like image 78
Thijs van Dien Avatar answered Oct 02 '22 08:10

Thijs van Dien


My mistake was a typo on detail.html:

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

should have been

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

It took a while for me to realise the django traceback page was pointing me to the relevant line of code the whole time. :$

like image 27
dmvianna Avatar answered Oct 02 '22 09:10

dmvianna