Django教程:反向&#39;详细信息&#39;有参数&#39;(&#39;&#39;,)&#39;未找到。尝试了1种模式:[&#39;民意调查\\ /(?P <question_id> [0-9] +)\\ / $&#39;]

时间:2018-03-18 21:47:07

标签: django

当我遇到这个问题时,我正在关注Django教程 我试图复制粘贴并一次又一次地阅读教程,但我无法修复它。

错误是:&#34;反转&#39;详细信息&#39;未找到。 &#39;细节&#39;不是有效的视图函数或模式名称。&#34;

错误追溯:

Environment:


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

Django Version: 2.0.3
Python Version: 3.5.2
Installed Applications:
['polls',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
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 /home/cristian/Desktop/build/polls/templates/polls/index.html, error at line 1
   Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$']
   1 : <li><a href=" {% url 'detail' question.id %} ">{{ question.question_text }}</a></li>

Traceback:

File "/home/cristian/.local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/home/cristian/.local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/home/cristian/.local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/cristian/Desktop/build/polls/views.py" in index
  10.     return render(request, 'polls/index.html', context)

File "/home/cristian/.local/lib/python3.5/site-packages/django/shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
  62.     return template.render(context, request)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/base.py" in render
  175.                     return self._render(context)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/home/cristian/.local/lib/python3.5/site-packages/django/template/defaulttags.py" in render
  447.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/home/cristian/.local/lib/python3.5/site-packages/django/urls/base.py" in reverse
  88.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "/home/cristian/.local/lib/python3.5/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  632.         raise NoReverseMatch(msg)

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


views.py:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
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})

models.py

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published', null=True)
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

urls.py

from django.urls import path

from . import views

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'),
]

的index.html

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

detail.html

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

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action={% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

我希望你能帮助我,谢谢。

1 个答案:

答案 0 :(得分:1)

错误发生在index.html

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

删除index.html中的url详细信息并将其放在details.html中。正如您所看到的,网址调度程序找不到您的网址,因为没有可用的投票ID。