Django 教程中的 NoReverseMatch 错误:参数未被拾取



我在学习 Django 教程时遇到以下错误:Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\/(?P<question_id>[0-9]+)\/$']

从这个答案来看,问题似乎是该论点没有在第 9 行传递results.html.

这个答案表明它应该是question.id但这就是我所拥有的。所以我不确定下一步该怎么做。部分跟随错误。当我从模板中删除第 9 行(包括此链接(时。感谢帮助。抱歉,如果之前已经问过这个问题 - 我觉得我到处都看过。

希望这是所有相关代码。(在出现几次错误后,我复制并粘贴了教程中的所有内容以防止拼写错误。

追踪

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:UsersUserDropboxPersonalProjectsPythonDjangodjango-tutmysitepollstemplatespollsresults.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:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangocorehandlersexception.py" in inner
35.             response = get_response(request)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangocorehandlersbase.py" in _get_response
128.                 response = self.process_exception_by_middleware(e, request)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangocorehandlersbase.py" in _get_response
126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersUserDropboxPersonalProjectsPythonDjangodjango-tutmysitepollsviews.py" in results
19.     return render(request, 'polls/results.html', {question:question})
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangoshortcuts.py" in render
36.     content = loader.render_to_string(template_name, context, request, using=using)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplateloader.py" in render_to_string
62.     return template.render(context, request)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplatebackendsdjango.py" in render
61.             return self.template.render(context)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplatebase.py" in render
175.                     return self._render(context)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplatebase.py" in _render
167.         return self.nodelist.render(context)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplatebase.py" in render
943.                 bit = node.render_annotated(context)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplatebase.py" in render_annotated
910.             return self.render(context)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangotemplatedefaulttags.py" in render
447.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangourlsbase.py" in reverse
88.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:UsersUserAppDataLocalProgramsPythonPython36-32Libsite-packagesdjangourlsresolvers.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]+)\/$']

投票/网址.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'),
]

我的网站/网址.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'),
]

投票/结果

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

投票/视图.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,)))

哇,这个花了我一段时间才发现。结果函数的最后一行有拼写错误。这:

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

应该是:

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

第一question周围有引号.

最新更新