Django教程:“详细信息”不是有效的视图函数或模式名称

时间:2018-12-08 03:31:23

标签: python django

我正在使用Windows XP,Python 3.4和Django 2.0.2

我是Django的新手,正在尝试按照

中的说明进行操作

https://docs.djangoproject.com/en/2.0/intro/tutorial04/

Django教程。我最可能犯的错误是我没有切 并将代码粘贴到正确的位置。这对我有帮助(可能 其他),如果本教程的作者引用了以下内容的完整列表: 每个阶段的py和html文件(不仅仅是代码的一部分)。

我遇到以下错误:

http://127.0.0.1:8000/polls/

`     / polls /
处的NoReverseMatch     找不到“详细信息”的相反内容。 'detail'不是有效的视图函数或模式名称。
    请求方法:GET
    要求网址:http://127.0.0.1:8000/polls/
    Django版本:2.0.2
    异常类型:NoReverseMatch
    异常值:
    找不到“详细信息”的相反内容。 'detail'不是有效的视图函数或模式名称。
    异常位置:_reverse_with_prefix中的C:\ programs \ python34 \ lib \ site-packages \ django \ urls \ resolvers.py,行632
    Python可执行文件:C:\ programs \ python34 \ python.exe
    Python版本:3.4.3
    Python路径:
    ['Y:\ mysite \ mysite',
     'C:\ WINDOWS \ system32 \ python34.zip',
     'C:\ programs \ python34 \ DLLs',
     'C:\ programs \ python34 \ lib',
     'C:\ programs \ python34',
     'C:\ programs \ python34 \ lib \ site-packages']
    服务器时间:2018年12月6日,星期四15:35:56 -0600
    模板渲染期间发生错误

在模板Y:\ mysite \ mysite \ polls \ templates \ polls \ index.html中,第4行错误
找不到“详细信息”的相反内容。 'detail'不是有效的视图函数或模式名称。

1   {% if latest_question_list %}
2       <ul>
3       {% for question in latest_question_list %}
4           <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
5       {% endfor %}
6       </ul>
7   {% else %}
8       <p>No polls are available.</p>
9   {% endif %}

`

读取的错误流结尾

    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail'
is not a valid view function or pattern name.
[06/Dec/2018 15:35:57] "GET /polls/ HTTP/1.1" 500 127035
Not Found: /favicon.ico
[06/Dec/2018 15:35:58] "GET /favicon.ico HTTP/1.1" 404 2078


在学习本教程之后,我有以下文件:

Y:\ mysite \ mysite \ polls \ models.py

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    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


Y:\ mysite \ mysite \ polls \ urls.py

from django.urls import path

from . import views
app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]


Y:\ mysite \ mysite \ polls \ views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Question
from django.views import generic

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
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):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    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,))


Y:\ mysite \ mysite \ polls \ templates \ polls \ detail.html

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

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

<form action="{% url 'polls:vote' question.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>


Y:\ mysite \ mysite \ polls \ templates \ polls \ index.html

`     
{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}
`  


Y:\ mysite \ mysite \ polls \ templates \ polls \ results.html

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


有人可以告诉我我在做什么吗?

我所有的HTML和PY文件都是从 Django Tutorial. 如果有人建议更改PY文件的HTML,那将非常 如果该人列出了完整的修改文件(而不仅仅是 变化)。
谢谢!

1 个答案:

答案 0 :(得分:0)

代替

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

使用

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

因为民意调查应用程序的网址包含在urlpatterns(与urls.py位于同一文件夹中)的settings.py中,所以名称为polls

urlpatterns = [
    ...
    path('', include('polls.url', name='polls')
]