我正在关注 django 2.0 教程“2.6.2 使用通用 View :代码越少越好”,并尝试将函数 View 转换为类 View 。
它抛出这样的错误:
TemplateDoesNotExist at /polls/1/results/
polls/question_detail.html
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/results/
Django Version: 2.0.4
我用官方资料查了一下代码
class ResultsView(generic.DetailView):
model = Question
template = 'polls/results.html'
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 did'nt select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
当我尝试提交投票时出现错误:
polls/detail.html
模板在带有函数 View 时可以正常工作:
<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>
我的代码有什么问题?
最佳答案
默认情况下,polls
应用中Question
模型的DetailView
使用模板polls/question_detail.html
.
如果你想覆盖它,你需要使用 template_name
。您已经设置了template
,这不会有任何效果。应该是:
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
...
关于python - 尝试在详细 View 中覆盖模板名称时出现 TemplateDoesNotExist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50116204/