Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...