首页 > 解决方案 > 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:\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]+)\\/$']

民意调查/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'),
]

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

民意调查/结果

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

民意调查/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,)))

标签: pythondjangodjango-urls

解决方案


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

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

应该:

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

在第一个周围加上引号question


推荐阅读