python - Django 教程:'detail' 不是有效的视图函数或模式名称
问题描述
我正在使用 Windows XP、Python 3.4 和 Django 2.0.2
我是 Django 新手,正在尝试按照
https://docs.djangoproject.com/en/2.0/intro/tutorial04/
Django 教程。我犯的最可能的错误是我没有在正确的位置剪切和粘贴代码。如果本教程的作者能够参考每个阶段的 py 和 html 文件的完整列表(不仅仅是代码的一部分),这将对我(可能还有其他人)有所帮助。
我有以下错误:
` NoReverseMatch at /polls/
Reverse for 'detail' 未找到。'detail' 不是有效的视图函数或模式名称。
请求方法:GET
请求 URL: http: //127.0.0.1
:8000/polls/
Django 版本:2.0.2
异常类型:NoReverseMatch
异常值:
未找到“详细信息”的反向。'detail' 不是有效的视图函数或模式名称。
异常位置:C:\programs\python34\lib\site-packages\django\urls\resolvers.py 在 _reverse_with_prefix,第 632 行
Python 可执行文件:C:\programs\python34\python.exe
Python 版本:3.4.3
Python 路径:
['Y:\mysite\mysite',
'C:\WINDOWS\system32\python34.
'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 行出现错误
Reverse for 'detail' not found。'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 教程
中剪切和粘贴的
。
如果有人建议对 PY 文件的 HTML 进行更改,那么如果该人列出完整的修改文件(而不仅仅是更改)将会非常有帮助。
谢谢!!
解决方案
代替
<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>
因为投票应用程序的 url 包含在urlpatterns
(urls.py
与 位于同一文件夹中settings.py
)中,名称polls
如下:
urlpatterns = [
...
path('', include('polls.url', name='polls')
]
推荐阅读
- amazon-web-services - AWS Cloudformation 创建的角色未显示在身份池下拉列表中
- nmake - 计算的宏名称
- php - 当我设置配置数据库时,它正在重置我的数据库连接
- c - 如何在 0 和 max 之间生成随机双精度(在 C 中)?
- android - 从 json api 获取嵌套值
- salesforce - 检查一百万条记录中是否存在数千条记录的有效方法
- javascript - 错误消息:未捕获的 TypeError:items.appendChild 不是函数
- html - Bootstrap 4 中的中心图像和 div 底层
- grammar - 这个递归规则中的顺序如何不给出相同的结果?
- c++ - 如何将调试器附加到 google v8?