Django 2.0转换为通用类视图时出现TemplateDoesNotExist错误
嘿,我一眼就瞅出问题出在哪啦!
问题根源与修复方案
核心错误:属性名拼写不对
你在ResultsView类里写的是template = 'polls/results.html',但Django的DetailView通用视图用来指定自定义模板的属性名是**template_name**,不是template!
因为你没正确指定模板路径,Django就启动了默认模板查找规则:应用名/模型类名小写_detail.html,也就是polls/question_detail.html,这就是为啥会报找不到这个模板的错误。
修正后的代码
把属性名改过来就行,代码如下:
class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' # 这里把template改成template_name
额外小提示(针对你没写完的vote函数)
如果你的vote函数是处理投票逻辑的,注意它作为处理POST请求的视图,要确保逻辑正确,比如获取选项、计数更新后重定向到结果页(避免重复提交),给你补个完整的参考示例:
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Question, Choice 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): # 没选选项的话,返回投票页面并提示错误 return render(request, 'polls/detail.html', { 'question': question, 'error_message': "你还没选任何选项哦!", }) else: selected_choice.votes += 1 selected_choice.save() # 重定向到结果页,防止刷新重复提交 return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
验证步骤
- 保存修正后的
ResultsView代码 - 重启Django开发服务器(有时候自动重载可能没触发,手动重启更稳妥)
- 再次访问
http://127.0.0.1:8000/polls/1/results/,就能正常加载你的polls/results.html模板啦!
内容的提问来源于stack exchange,提问作者Wizard
相关产品推荐
相关产品推荐

