【问题标题】:Django Tutorial: 'detail' is not a valid view function or pattern nameDjango 教程:'detail' 不是有效的视图函数或模式名称
【发布时间】:2019-05-09 19:02:07
【问题描述】:

我正在使用 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 进行更改,那将是非常 如果该人列出完整的修改文件(不仅仅是 变化)。
谢谢!!

【问题讨论】:

标签: python django


【解决方案1】:

而不是

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

因为投票应用程序的网址包含在 urls.py(与 settings.py 位于同一文件夹中)中的 urlpatterns 中,名称为 polls,如下所示:

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

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 2018-11-29
    • 2020-03-13
    • 2020-08-26
    • 1970-01-01
    • 2018-01-25
    • 2019-06-27
    • 2019-02-15
    • 2019-04-21
    相关资源
    最近更新 更多